RailsCasts中文版,#8 Layouts and content_for 使用content_for方法定制布局文件
来源:互联网 发布:h3c端口镜像配置 编辑:程序博客网 时间:2024/06/09 22:43
下面分别是全局的布局文件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.
- RailsCasts中文版,#8 Layouts and content_for 使用content_for方法定制布局文件
- RailsCasts8 Layouts and content_for Layouts及content_for
- RailsCasts中文版,#7 All About Layouts 页面关联布局文件
- layout与content_for
- rails yield与content_for
- RailsCasts中文版,#2 Dynamic find_by Methods 使用动态的find_by方法进行查找操作
- Rails宝典之第八式: layout与content_for
- rails中 yeild 与 content_for之间的区别
- rails中 yeild 与 content_for之间的区别
- rails中 yeild 与 content_for之间的区别
- RailsCasts中文版,#3 Find Through Association 使用级联查询
- Android提高显示布局文件的性能,使用include标签重用layouts
- RailsCasts中文版,#4 Move Find into Model 将查询方法从控制器上移至模型
- RailsCasts中文版,#5 Using with_scope 对find方法限定作用域
- RailsCasts中文版,#16 Virtual Attributes 虚拟属性
- RailsCasts中文版,#16 Virtual Attributes 虚拟属性
- SWT布局(Layouts)
- Layouts(布局)
- java获取项目路径
- Struts1和Spring整合三种启动Spring容器的方式
- opention selected jstl标签
- Linux
- 统计出每个编号对应离当前日期最近第一条记录
- RailsCasts中文版,#8 Layouts and content_for 使用content_for方法定制布局文件
- SQL语言分类
- 一条SQL语句,关于字符分割关联多条记录的问题
- html5跨平台---开篇介绍
- hdoj2553N皇后问题
- 一条Sql语句连接多个数据
- C4.5决策树算法
- MAKE 介绍
- Java代码混肴器之-Jrock