Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: about yield

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:

  1. Where can I find the yield content of the first <%=yield%> under <body>.
  2. 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 of some_car?
like image 804
Mellon Avatar asked Oct 21 '11 10:10

Mellon


People also ask

How does yield work in Rails?

When yield is called in side a method then method requires a block with in it. A block is simply a chunk of code, and yield allows us to inject that code at some place into a method. Simple Yield: When the yield keyword used inside the body of a method, will allow us to call that method with a block of code.

What is yield tag in rails?

It tells Rails to put your view content to this block (which is called by yield ) at that place in the layout file.

What does yield do in ERB?

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 .

What is the purpose of yield in Ruby?

yield tells ruby to call the block passed to the method, giving it its argument. yield will produce an error if the method wasn't called with a block where as return statement don't produces error.


1 Answers

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. For example, if your cars/show page has a specific html snippet that you want to render in the footer, you could add the following to your show template and the car_general layout:

show.html.erb:

<% content_for :footer do %>   This content will show up in the footer section <% end %> 

layouts/car_general.html.erb

<%= yield :footer %> 

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_for is 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.

like image 184
Peter Brown Avatar answered Sep 28 '22 08:09

Peter Brown