nop*_*ole 5 ruby-on-rails ruby-on-rails-3
简短的问题是:子页面怎么样
<% content_for :title do 'Showing product' end %>
Run Code Online (Sandbox Code Playgroud)
设置:title主要布局?
细节:
我们可以在应用程序布局中使用 application.html.erb
<title><%= content_for :title %>
...
<%= yield %>
Run Code Online (Sandbox Code Playgroud)
我认为yield返回子页面的内容,例如from show.html.erb,它包含的内容:
<% content_for :title do 'Showing product' end %>
Run Code Online (Sandbox Code Playgroud)
怎么能以:title某种方式被上面的东西使用yield?我认为title首先评估部件,然后评估yield,那么如何:title追溯设置<title>标签的内容?
简短回答:作弊.
答案很长:ActionView重新定义了产量,因此它与我们所知道的产品不同,并且非常喜欢好的红宝石.实际上,模板文件在布局文件之前呈现,然后布局文件中的yield将被已呈现的模板替换.content_for块被保存到类变量中,因此您可以稍后从布局中访问它们.
我title在我的application_helper.rb文件中定义了一个helper方法,如下所示:
module ApplicationHelper
def title(page_title)
content_for(:title){ page_title }
page_title
end
end
Run Code Online (Sandbox Code Playgroud)
然后在我的内容ERB文件的顶部,我可以做到这一点
<% title "Rails Rocks" %>
Other regular content
Run Code Online (Sandbox Code Playgroud)
并在 application.html.erb
<html>
<head>
<% title = yield(:title).chop! %>
<title><%= title || 'Default Title' %></title>
</head>
<body>
<h1 class="title"><%= title %></h1>
</body>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5183 次 |
| 最近记录: |