开发者

How does Ruby on Rails use yield for layouts?

开发者 https://www.devze.com 2023-02-07 23:44 出处:网络
yield is used to call a block. How does this work in Rails where yield is used for layouts? -# application.html.haml

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 block开发者_开发知识库s somewhere or is the method simply overridden?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号