(â»12æã®1æ¥ãã25æ¥ã¾ã§ãæ¥æ¿ãã㧠Ruby ã® Tips ãç´¹ä»ããã¤ãã³ãã Ruby Advent Calendar jp: 2009 ã® 12 æ¥ç®ã§ããæ¨æ¥ã¯ id:ohac ããã§ãããææ¥ã¯うづら(udzura) ããã®äºå®ã§ãã)
Railsãã¿ãã²ã¨ã¤æ¸ãããã¨æãã¾ãã
titleãviewã§è¨å®ããã
ã»ã¨ãã©ã®Rails使ãã®çããã¯ãããããä¸è¨ã®ãããªlayoutã使ããã¨ã§viewãDRYã«ãã¦ããã®ã§ã¯ã¨æãã¾ãã
app/views/layouts/application.html.erb
<html> <head> <title>ã¿ã¤ãã«</title> </head> <body> <%= yield %><!-- ãããåviewãã¡ã¤ã«ã§å®ç¾©ãã --> </body> </html>
ã§ããããã ã¨ã¿ã¤ãã«ãåºå®ã«ãªã£ã¦ãã¾ãã¾ãããã¢ã¯ã·ã§ã³ãã¨ã«ã¿ã¤ãã«ãå¤ãããã¨ããã¨ãä¸è¨ã®ããã«ãã¿ã¤ãã«ãã¤ã³ã¹ã¿ã³ã¹å¤æ°ã«ãã¦controllerå´ã§è¨å®ããæ¹æ³ãæãã¤ãã¾ãã
app/views/layouts/application.html.erb
<html> <head> <title><%= @title %></title> </head> <body> <%= yield %><!-- ãããåviewãã¡ã¤ã«ã§å®ç¾©ãã --> </body> </html>
app/controllers/main_controller.rb
class MainController < ApplicationController def index @title = "hoge" end def show @title = "fuga" end end
ããããæ¬æ¥ããã¼ã¸ãã¨ã®ã¿ã¤ãã«ã¯viewã§è¨å®ããæ¹ãMVCçã«ããã®ã§ã¯ãªãã§ããããã*1
ããã§content_forã§ãã
ãããªæã®ããã«ãRailsã«ã¯content_forã¨ããã¡ã½ãããç¨æããã¦ãã¾ãããã®ã¡ã½ããã使ãã¨ãå¼æ°ã«å¯¾å¿ããyieldã¨ãããã¯ã®æ»ãå¤ãç½®ãæããã¾ããå ·ä½çã«ã¯ä¸è¨ã®ããã«ä½¿ãã¾ãã
app/views/layouts/application.html.erb
<html> <head> <title><%= yield :title %></title><!-- viewã§å®ç¾©ããcontent_for :titleã®ãããã¯ã®å 容ã§ç½®ãæãã --> </head> <body> <%= yield %> </body> </html>
app/views/main/index.html.erb
<% content_for :title do %> hoge <% end %>
ããã§viewã§ã¿ã¤ãã«ãè¨å®ãããã¨ãåºæ¥ã¾ãã*2ããã¡ããjavascriptãcssãåãããã«è¨å®ãããã¨ãåºæ¥ã¾ããããã§controllerãå°ããã£ãããã¾ãããï¼
*1:ãã®ä¾ã§ã¯çç¥ãã¦ãã¾ãããã¿ã¤ãã«ä»¥å¤ã«ãjavascriptãcssãåãæ¿ããããã®è¨å®ãcontrollerã®ã¤ã³ã¹ã¿ã³ã¹å¤æ°ã«æ¸ãã¦ãã人ãå¤ãã§ãããã
*2:å®éã¯helperã«titleã¡ã½ãããªã©ãå®ç¾©ãã¦ãã®ä¸ã«æ¸ããæ¹ãããã¨æãã¾ã