RailsCasts中文版,#8 Layouts and content_for 使用content_for方法定制布局文件

下面分别是全局的布局文件application.rhtmlindex 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]

当请求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>

增加了content_for的index.rhtml[1]

下面对布局文件进行修改。将需要输出定制内容的地方增加yield方法,接受之前定义的名字作为参数。如此一来,加载布局文件时候看到了yield :head就会执行之前定义的代码块并将返回结果加入到布局文件中。

...
  <head>
    <title>Todo List</title>
    <%= stylesheet_link_tag 'project' %>
    <%= yield :head %>
  </head>
...

刷新之后从源代码可以看出,在index中定义的CSS文件已经生效了。

E008I01

content_for为我们提供在Action中定制布局文件定义的能力。诸如为某些指定的Action中增加用于显示菜单,滚动条等效果的CSS引用等。

注:
  1. 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.

原文链接:http://railscasts.com/episodes/8-layouts-and-content-for

posted on 2012-11-24 09:21  边晓宇  阅读(929)  评论(0编辑  收藏  举报