ruby-on-rails 编写Rails布局

14ifxucb  于 2023-10-21  发布在  Ruby
关注(0)|答案(1)|浏览(94)

假设我有:

# layouts/application.html.erb

<html>
  <head>
    <body>
      <p>Hi</p>
      <%= yield :toolbar1 %>
      <%= yield :toolbar2 %>
      <%= yield %>
    </body>
  </head>
</html>

根据具体情况,还有两个额外的布局:

# layouts/toolbar1.html.erb
<% content_for :toolbar1 do %>
  <p>toolbar1</p>
<% end %>

# layouts/toolbar2.html.erb
<% content_for :toolbar2 do %>
  <p>toolbar2</p>
<% end %>

如何在每个控制器的基础上有条件地加载:toolbar1toolbar2,例如:

# Controller where *only* :toolbar1 should be present on show action
class TestController < ApplicationController
  def show
    render "show", layout: "toolbar1"
  end
end

.不起作用,因为它只是尝试加载toolbar1.html.erb而不加载application.html.erb布局。基本上,我想组成布局控制器的控制器(路线的路线,如果你喜欢)。

oxosxuxt

oxosxuxt1#

可能有更好的方法来做你需要做的事情。
但这是可行的:

# layouts/toolbar1.html.erb

<% content_for :toolbar1 do %>
  <p>toolbar1</p>
<% end %>

<%= render template: "layouts/application" %>

其余的都一样。
作为替代方案,模板继承可能对此有用:

# app/views/application/_toolbar.html.erb

# empty
<!-- layouts/application.html.erb -->

<html>
  <head></head>
  <body>
    <%= render "toolbar" %>
    <%= yield %>
  </body>
</html>

然后覆盖_toolbar partial:

<!-- app/views/*/_toolbar.html.erb -->

<div>a toolbar for some controller</div>
  • https:guides.rubyonrails.org/layouts_and_rendering.html#template-inheritance*

相关问题