For example: content_for(:stuff)
vs yield :stuff
I know they are implemented slightly differently, but is there any real functionality difference?
Is there a generally accepted best practice?
Without any arguments, yield will render the template of the current controller/action. So if you're on the cars/show page, it will render views/cars/show. html. erb . When you pass yield an argument, it lets you define content in your templates that you want to be rendered outside of that template.
The layouts removes code duplication in view layer. You are able to slice all your application pages to blocks such as header, footer, sidebar, body and etc. This is an example of typical web application page, almost every site has these blocks. And as a rule the body block differs on each page.
2.2. By default, if you use the :plain option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the layout: true option and use the . text. erb extension for the layout file.
Rendering is the ultimate goal of your Ruby on Rails application. You render a view, usually . html. erb files, which contain a mix of HMTL & Ruby code. A view is what the user sees.
yield
is how you specify where your content areas is going to go within a layout. You might have something like this:
<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 :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.
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.
Calling #content_for stores a block of markup in an identifier for later use. In order to access this stored content in other templates, helper modules or the layout, you would pass the identifier as an argument to content_for. yield can still be used to retrieve the stored content, but calling yield doesn't work in helper modules, while content_for does....more: http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With