content_for与部分收益率 [英] content_for vs yield in partials
问题描述
在具有HAML(3.1.4)的rails 3.0中
In rails 3.0 with HAML (3.1.4) I have
-
一些类似模板的 partial ,例如_template.html.haml:
some template-like partial, like _template.html.haml:
.panel.top
= yield :panel_top
.content
= yield
另外一个 partial ,它将使用上一个模板显示(所有这些内容都是使用AJAX呈现的,但这无关紧要)
some another partial which will be displayed using prev template (all this stuff is rendered using AJAX, but this doesn't matter)
- content_for :panel_top do
.title.left
= title
content text
这在Rails 3.0
但是,升级到 3.2 后,此操作将失败! Yiels只会产生内容文字",所以我有两次内容文字",根本没有标题
But, after upgrade to 3.2 this fails! Yiels just yields "content text", so I have "content text" twice and no title at all
仅将= yield :panel_top
更改为= content_for :panel_top
适用于3.2
only changing = yield :panel_top
to = content_for :panel_top
works for 3.2
我不确定该解决方案是否可行,如果它是稳定的或推荐使用的,我找不到有关yield
处理,Rails 3.1发行说明和3.2发行说明中更改的任何注释.
I am not sure that this solution is ok, and if it is stable or recommended, I cannot find any notes about changes in yield
processing nor in Rails 3.1 release notes, nor in 3.2 ones.
您能帮忙组织内部零件的最佳方法吗?
Can you help what is the best way to organize yield
ing inside partials?
推荐答案
从Rails 3.0到Rails 3.2 content_for
确实已更改:
From Rails 3.0 to Rails 3.2 content_for
was really changed:
3.0 :
def content_for(name, content = nil, &block)
content = capture(&block) if block_given?
@_content_for[name] << content if content
@_content_for[name] unless content
end
3.2 :
def content_for(name, content = nil, &block)
if content || block_given?
content = capture(&block) if block_given?
@view_flow.append(name, content) if content
nil
else
@view_flow.get(name)
end
end
这向我们展示了3.2 content_for
中的版本也可以显示/插入内容,不仅将其存储在命名节中.
This shows us, that from 3.2 content_for
works for showing/inserting content too, not only store it for named section.
此外,如果您尝试调试yield
逻辑,则会发现它会在content_for
正确初始化之前产生.
Also, if you make an attempt to debug yield
logic you'll se that it yields before content_for
is correctly initialized.
因此,将片段缓存排除在讨论之外,我可以得出结论,content_for
是更可取的方式,可以在顶级布局之外的任何位置插入命名节.在助手和其他情况下,yield
应该导致错误的结果.
So, leaving fragment caching out of this discussion I can conclude that content_for
is preferrable way to insert named sections anywhere except top-level layouts. In helpers and other situations yield
should render wrong results.
这篇关于content_for与部分收益率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!