下面分别是全局的布局文件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>
上面是application.rhtml[1]
<h2>Projects</h2>
<ul>
<% for project in @projects %>
<li><%= project.name %></li>
<% end %>
</ul>
上面是index.rhtml [1]
当请求index
action的时候,页面的绘制会基于全局布局文件。 (不清楚布局文件概念的请移步《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>
增加了content_for的index.rhtml[1]
下面对布局文件进行修改。将需要输出定制内容的地方增加yield
方法,接受之前定义的名字作为参数。如此一来,加载布局文件时候看到了yield :head
就会执行之前定义的代码块并将返回结果加入到布局文件中。
...
<head>
<title>Todo List</title>
<%= stylesheet_link_tag 'project' %>
<%= yield :head %>
</head>
...
刷新之后从源代码可以看出,在
index
中定义的CSS文件已经生效了。
content_for
为我们提供在Action中定制布局文件定义的能力。诸如为某些指定的Action中增加用于显示菜单,滚动条等效果的CSS引用等。
注:
- Rails 2及以上版本,布局文件不再使用
.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.