Ruby on Rails 的“content_for :title"如何?得到后来分配的东西? [英] How can Ruby on Rails's "content_for :title" get something that is assigned later?
问题描述
简短的问题是:子页面如何
The short question is: how can a subpage's
<% content_for :title do 'Showing product' end %>
为主布局设置:title
?
详情:
我们可以在应用布局中使用application.html.erb
We can use in the application layout application.html.erb
<title><%= content_for :title %>
...
<%= yield %>
并且我认为 yield
返回子页面的内容,例如来自 show.html.erb
的内容,其中包含:
and I think yield
returns the content for a subpage, such as from show.html.erb
, where it contains:
<% content_for :title do 'Showing product' end %>
:title
如何以某种方式被 yield
之上的东西使用?我以为先评估 title
部分,然后是 yield
,那么 :title
如何追溯设置 的内容
标签?
How can the :title
somehow get used by something above the yield
? I thought the title
part is evaluated first, and then the yield
, so how can the :title
retroactively set the content for the <title>
tag?
推荐答案
简答:作弊.
长答案:ActionView 重新定义了产量,因此它与我们从好的红宝石中了解和喜爱的产量不同.事实上,模板文件在布局文件之前渲染,然后布局文件中的产量将被已经渲染的模板替换.content_for
块保存在类变量中,以便您以后可以从布局中访问它们.
Long answer: ActionView redefines yield so it is not the same yield we know and love from good ol' ruby. In fact the template file is rendered before the layout file and then the yield in the layout file will be substituted by the already rendered template. content_for
blocks are saved into class variables and so you can later access them from your layout.
这篇关于Ruby on Rails 的“content_for :title"如何?得到后来分配的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!