user142019
user142019

Reputation:

How does Ruby on Rails use yield for layouts?

yield is used to call a block. How does this work in Rails where yield is used for layouts?

-# application.html.haml
%body= yield

Does it use blocks somewhere or is the method simply overridden?

Upvotes: 21

Views: 15046

Answers (2)

Pan Thomakos
Pan Thomakos

Reputation: 34350

By default all Ruby functions can be passed a block:

def twice
  yield
  yield
end

> twice { print 'hi ' }
=> hi hi

The best way to think of a layout is a method that is called with a block.

When Rails renders a template, it is actually making a call to Layout#render. Layout#render accepts a default block. By default Rails passes your view as this block. This means that calling yield from within your layout is like calling the default block, which in this case is your view.

Upvotes: 9

Shaun
Shaun

Reputation: 4799

Technically, yield is calling a block in this context as well. However, the block is the view your controller action was told to render.

For example, let's say you have a StaticContentController that has an index action on it that represented your home page. With routes configured correctly, you visit your home page. Rails will load the layout file in views/layouts that is appropriate for that controller (application.html.haml, unless you overrode this with a layout for your controller). When it reaches the yield command, it inserts the view at views/static_content/index.html.haml at the location where yield is inside your layout. Then, it loads the rest of your layout file.

Upvotes: 21

Related Questions