I saw some code in a Rails v2.3 app.
In layout/car_general.html.erb (this view is called by a method in cars_controller) , I saw the code:
<body>
<%= yield %>
<%= javascript_include_tag 'jquery-1.4.2.min' %>
<% javascript_tag do %>
<%= yield :jstemplates %>
var some_car = new Object;
<%= yield :some_car %>
<% end -%>
</body>
Two questions to ask:
- Where can I find the yield content of the first <%=yield%> under
<body>. - Is it a rails specific way to include js code in a view by using
<%= yield :jstemplates %>and what about<%= yield :some_car %>, is it point to a view or just to show the value ofsome_car?
Without any arguments, yield will render the template of the current controller/action. So if you’re on the
cars/showpage, it will renderviews/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. For example, if your
cars/showpage has a specific html snippet that you want to render in the footer, you could add the following to your show template and thecar_generallayout:show.html.erb:
layouts/car_general.html.erb
The Rails Guide has a good section on using yield and content_for: http://guides.rubyonrails.org/layouts_and_rendering.html#understanding-yield
The API documentation for
content_foris helpful too and has some other examples to follow. Note that it’s for Rails 3.1.1 , but this functionality has not changed much since 2.3, if at all and should still apply for 3.0.x and 3.1.x.