Ruby on Rails 如何使用 Yield 进行布局?
yield
用于调用区块。在使用 yield
进行布局的 Rails 中,这是如何工作的?
-# application.html.haml
%body= yield
它是否在某处使用块或者该方法只是被覆盖?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从技术上讲,yield 也在这种情况下调用块。但是,该块是您的控制器操作被告知要渲染的视图。
例如,假设您有一个
StaticContentController
,其中有一个代表您主页的index
操作。正确配置路由后,您将访问您的主页。 Rails 将在适合该控制器的views/layouts
中加载布局文件(application.html.haml
,除非您使用控制器的布局覆盖它)。当它到达yield
命令时,它会将视图插入views/static_content/index.html.haml
中yield
所在位置。布局。然后,它加载布局文件的其余部分。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 anindex
action on it that represented your home page. With routes configured correctly, you visit your home page. Rails will load the layout file inviews/layouts
that is appropriate for that controller (application.html.haml
, unless you overrode this with a layout for your controller). When it reaches theyield
command, it inserts the view atviews/static_content/index.html.haml
at the location whereyield
is inside your layout. Then, it loads the rest of your layout file.默认情况下,所有 Ruby 函数都可以传递一个块:
考虑布局的最佳方式是使用块调用的方法。
当 Rails 渲染模板时,它实际上是在调用 Layout#render。 Layout#render 接受默认块。默认情况下,Rails 将您的视图作为此块传递。这意味着从布局中调用yield就像调用默认块一样,在本例中是您的视图。
By default all Ruby functions can be passed a block:
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.