RubyのフレームワークSinatraで、erbテンプレートを使う方法と、テンプレートでRubyの変数を使う方法。
テンプレートを使う
erb :テンプレート名
で、erbテンプレートを使うことができる。
<test.rb>
get "/" do erb :index end
views
というディレクトリを作り、その中にindex.erb
というファイルを作る。
views
はSinatraで決められている名称だが、テンプレート名はindex以外にも好きな名前でいくつでも作ることができる。
変数を使う
テンプレート内で使いたい変数名は、rbファイルで、@name
のように頭に@
をつける。
テンプレート(index.erbなど)内では、<%= @name %>
のように、変数名を<%= %>
で囲む。
<test.rb>
require "sinatra" require "sinatra/reloader" get "/" do @now = Time.now erb :index end
<index.erb>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Sinatra Practice</title> </head> <body> <h1>Sinatra Practice</h1> <p>現在、<%= @now %>です。</p> </body> </html>
これでhttp://localhost:4567にアクセスすると、下記のように表示できる。