How does Ruby on Rails use yield for layouts? How does Ruby on Rails use yield for layouts? ruby ruby

How does Ruby on Rails use yield for layouts?


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.


By default all Ruby functions can be passed a block:

def twice  yield  yieldend> 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.