yield
is how you specify where your content areas is going to go within a layout. You might have something like this:
yield
是你指明您的内容将如何放在一个布局中。你可能会有这样的事情:
<div>
<h1> This is the wrapper!</h1>
<%= yield :my_content %>
</div>
content_for
is how you specify which content is going to be rendered into which content area. You might have something like this:
content_for你指定的内容将被渲染到内容区域。你可能会有这样的事情:
<% content_for :my_content do %>
This is the content.
<% end %>
The result would be
<div>
<h1> This is the wrapper!</h1>
This is the content.
</div>
They are opposite ends of the rendering process, with yield
specifying where content goes, and content_for
specifying what the actual content is.
他们在渲染过程的两端,与yield
规定内容去哪里,和content_for指定实际的内容是什么。
Is there a generally accepted best practice?
The best practice is to use yield
in your layouts, and content_for
in your views. There is a special second use for content_for
, where you give it no block and it returns the previously rendered content. This is primarily for use in helper methods where yield
cannot work. Within your views, the best practice is to stick to yield :my_content
to recall the content, and content_for :my_content do...end
to render the content.
最好的方法是将yield
用在layout中,content_for
用在view中;content_for
有另外的一种用法,当不传block给它时,它将返回之前呈现的内容;这主要用在helper中,yeild不能工作;在view中,content_for
最好用于呈现内容,yield
最好用于调取内容。
转自:http://stackoverflow.com/questions/13150983/rails-what-is-the-difference-between-content-for-and-yield