Ruby on Rails 如何使用 Yield 进行布局?

发布于 2024-10-15 02:34:43 字数 171 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼中杀气 2024-10-22 02:34:43

从技术上讲,yield 也在这种情况下调用块。但是,该块是您的控制器操作被告知要渲染的视图。

例如,假设您有一个 StaticContentController,其中有一个代表您主页的 index 操作。正确配置路由后,您将访问您的主页。 Rails 将在适合该控制器的 views/layouts 中加载布局文件(application.html.haml,除非您使用控制器的布局覆盖它)。当它到达 yield 命令时,它会将视图插入 views/static_content/index.html.hamlyield 所在位置。布局。然后,它加载布局文件的其余部分。

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.

淡淡绿茶香 2024-10-22 02:34:43

默认情况下,所有 Ruby 函数都可以传递一个块:

def twice
  yield
  yield
end

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

考虑布局的最佳方式是使用块调用的方法。

当 Rails 渲染模板时,它实际上是在调用 Layout#render。 Layout#render 接受默认块。默认情况下,Rails 将您的视图作为此块传递。这意味着从布局中调用yield就像调用默认块一样,在本例中是您的视图。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文