Mellon
Mellon

Reputation: 38842

Newbie question, what does 'yield' here means?

I saw someone's code in View/car.html.haml like followows:

%body
  =yield

Can anybody explain me the use of "=yield" here?

-where can I find the actual body part code?

-What does it means,

-why use it or in what situation we should use it?

Upvotes: 2

Views: 1775

Answers (3)

Jack Clarke
Jack Clarke

Reputation: 1

This above defined function is actually a generator function, in which we define a function normally but use the yield statement instead of return, indicating to the interpreter that this function should be treated as an iterator.

The yield statement pauses the function and saves the local state so that it can be resumed right where it left off.

When we will call this function,it gives us the output

val = countdown(5)
>>> val
<generator object countdown at 0x10213aee8>

The function has actually returned a generator object.So the generator functions are called in a different way in the below mentioned manner :

Generator objects execute when next() is called.

>>> next(val)
Starting
5 

Upvotes: 0

nzifnab
nzifnab

Reputation: 16092

Typically this will appear in a layout file (by default - views/layouts/application.html.haml). It simply tells Rails to render the content of the current action at that location.

So if you have views/layouts/application.html.haml with:

%body
  =yield

And you have views/posts/index.html.haml with:

%h1 This is the posts index page!  :D

Then when you go to an action that renders the posts index page (probably /posts), you will see the html that has that heading rendered at the location of the yield in your layout file:

<body>
  <h1>This is the posts index page! :D</h1>
</body>

This is particularly useful to include things like common page navigation markup, or headers that should show up on all pages without having to re-define the exact html in every view.

If you have a different layout for a separate section of your site you might render your view in the controller like this:

def index
  if signed_in?
    render :layout => 'application'
  else
    render 'user/unauthorized', :layout => 'external' and return
  end
end

Which will use the specified view, rendered inside the specified layout wherever the layout's yield occurs. In the else of the statement user/unauthorized.html.haml would be rendered within the layouts/external.html.haml layout, and in the signed_in? case you would get the posts/index.html.haml view rendered within the layouts/application.html.haml layout.

Upvotes: 4

mduvall
mduvall

Reputation: 1038

http://api.rubyonrails.org/classes/ActionView/Partials.html

The article above will explain what it means, the syntax is not the same since the documentation is in erb and you are dealing with haml. The actual body code is most likely in the _body.html.haml partial.

Upvotes: 1

Related Questions