How does Ruby on Rails use yield for layouts?

user142019 picture user142019 · Jan 31, 2011 · Viewed 14.3k times · Source

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?

Answer

Shaun picture Shaun · Feb 1, 2011

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.