チュートリアルをする。静的なページ作成
以下のチュートリアルをテスト駆動はやらずに実行してみる。railstutorial.jp
やることは二つのページHome, Helpに加えて三つ目のページAboutを作成しておく。
app/controllers/static_pages_controller.rb
class StaticPagesController < ApplicationController def home end def help end def about end end
app/views/static_pages/about.html.erb
<!DOCTYPE html> <html> <head> <title>Ruby on Rails Tutorial Sample App | About Us</title> </head> <body> <h1>About Us</h1> <p> The <a href="http://railstutorial.org/">Ruby on Rails Tutorial</a> is a project to make a book and screencasts to teach web development with <a href="http://rubyonrails.org/">Ruby on Rails</a>. This is the sample application for the tutorial. </p> </body> </html>
routes.rb
SampleApp::Application.routes.draw do get "static_pages/home" get "static_pages/help" get "static_pages/about" ... end
ローカルサーバーで確認。
app/views/static_pages/home.html.erb
をrubyの埋め込みを使って書き換える。
<% provide(:title, 'Home') %> <!DOCTYPE html> <html> <head> <title>Ruby on Rails Tutorial Sample App | <%= yield(:title) %></title> </head> <body> <h1>Sample App</h1> <p> This is the home page for the <a href="http://railstutorial.jp/">Ruby on Rails Tutorial</a> sample application. </p> </body> </html>
provideで:titleに文字列'HOME'を関連付け、yieldでその:titleの中身を取り出してテンプレートに挿入している。<% %>内はrubyが実行、<%= %>内はrubyが実行され結果がテンプレートに挿入される。
アプリ間に共通なレイアウト構造はapp/views/layouts/application.html.erbでまとめて定義できる。
<!DOCTYPE html> <html> <head> <title>Ruby on Rails Tutorial Sample App | <%= yield(:title) %></title> <%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %> <%= javascript_include_tag "application", "data-turbolinks-track" => true %> <%= csrf_meta_tags %> </head> <body> <%= yield %> </body> </html>
このbody内に対応するものを各home,help,aboutに書いておけば良くなる。
<% provide(:title, 'About Us') %> <h1>About Us</h1> <p> The <a href="http://railstutorial.jp/">Ruby on Rails Tutorial</a> is a project to make a book and screencasts to teach web development with <a href="http://rubyonrails.org/">Ruby on Rails</a>. This is the sample application for the tutorial. </p>
<% provide(:title, 'Home') %> <h1>Sample App</h1> <p> This is the home page for the <a href="http://railstutorial.jp/">Ruby on Rails Tutorial</a> sample application. </p>
<% provide(:title, 'Help') %> <h1>Help</h1> <p> Get help on the Ruby on Rails Tutorial at the <a href="http://railstutorial.jp/help">Rails Tutorial help page</a>. To get help on this sample app, see the <a href="http://railstutorial.jp/book">Rails Tutorial book</a>. </p>