RailsCasts中文版,#8 Layouts and content_for 使用content_for方法定制布局文件
下面分别是全局的布局文件application.rhtml及index Action页面定义:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html> <head> <title>Todo List</title> <%= stylesheet_link_tag 'application' %> </head> <body> <div id="container"> <h1>Todo List</h1> <%= yield %> </div> </body></html>
<h2>Projects</h2><ul><% for project in @projects %> <li><%= project.name %></li><% end %></ul>
当请求indexaction的时候,页面的绘制会基于全局布局文件。 (不清楚布局文件概念的请移步《RailsCasts中文版,#7 All About Layouts 页面关联布局文件》). 如果需要对当前关联的布局文件进行更加细节上的调整应该怎么做呢?比如说,想在index页面上使用不同于全局页面布局文件的CSS定义等。在页面中使用content_for方法可以实现想要的效果。content_for接受一个名称参数及代码块定义。代码块逻辑生成的内容将会被加载到布局文件中。
<% content_for :head do %> <%= stylesheet_link_tag 'projects' %><% end %><h2>Projects</h2><ul><% for project in @projects %> <li><%= project.name %></li><% end %></ul>
下面对布局文件进行修改。将需要输出定制内容的地方增加yield方法,接受之前定义的名字作为参数。如此一来,加载布局文件时候看到了yield :head就会执行之前定义的代码块并将返回结果加入到布局文件中。
... <head> <title>Todo List</title> <%= stylesheet_link_tag 'project' %> <%= yield :head %> </head>...
index中定义的CSS文件已经生效了。
content_for为我们提供在Action中定制布局文件定义的能力。诸如为某些指定的Action中增加用于显示菜单,滚动条等效果的CSS引用等。
.rhtml后缀,而是.html.erb。作者授权:Your welcome to post the translated text on your blog as well if the episode is free(not Pro). I just ask that you post a link back to the original episode on railscasts.com.