index.slimに変数を渡す
myapp.rb
get '/' do @tweets = client.user_timeline('naoyashiga') @pageTitle = "naoyashiga tweets" slim :index end
以前のエントリではhtmlにつぶやきを渡してはいませんでした。今回はindex.slimに変数を渡したいと思います。
・以前のエントリ
twitter gem(5.11.0)を使って自分のつぶやきを取得する - not good but great
slimの書き方
slimの書き方は下を参考にしました。
・参考
http://slim-lang.com/
Sinatraとhaml,slim - Qiita
変数の受け取り方
index.slimの位置
index.slimはviewsフォルダ以下に入れておきます。
「= @変数」で渡す
doctype html
html
head
title = @pageTitle
変数は「= @変数」で渡します。
配列を受け取る
doctype html html head title = @pageTitle body - for tweet in @tweets p = tweet.text p = tweet.favorite_count
user_timelineの返り値は配列になっています。配列は上のようにハイフンでRubyのコードを実行させる記述をします。tweetのテキストを取ったり、fav数を取得することが出来ました。
gem twitterの使い方を下を参考にしました。
Module: Twitter::REST::Timelines — Documentation for twitter (7.0.0)
Class: Twitter::Tweet — Documentation for twitter (7.0.0)