我有一个带有全局应用程序布局文件application.html.haml
的应用程序。然后,我有多个“控制器堆栈”:用于我们的主站点,管理门户和我们的业务站点。对于其中的每一个,控制器都在一个模块中,并且都来自同一个BaseController
。每个堆栈都有自己的布局文件。在堆栈中,一些控制器也有布局文件。
我希望所有视图(除非另有说明)在多层嵌套布局中呈现:application,“stack”,“controller”。
例如,对于Site::BlogController#show
操作,我想要使用rails进行渲染:
/site/blog/show.html.haml
内的/layouts/site/blog.html.haml
内的/layouts/site.html.haml
内{p> /layouts/application.html.haml
我很难理解如何将/layouts/site.html.haml
插入堆栈。看起来好像是自动的,rails会在应用程序布局中的控制器布局内呈现动作,但是,我看不到如何将布局“插入”渲染堆栈。
非常感谢任何帮助,但是,我已阅读所有导轨指南无效,因此指向http://guides.rubyonrails.org/layouts_and_rendering.html#using-nested-layouts的链接实际上没有用处。
答案 0 :(得分:18)
我重读了我发布的链接(http://guides.rubyonrails.org/layouts_and_rendering.html#using-nested-layouts)并意识到我错过了一个关键细节。
<%= render :file => 'layouts/application' %>
所以,在Site::BaseController
我打电话给layout 'site'
并在/layouts/site.html.haml
我有
= content_for :footer do
-#Content for footer
= render :file => 'layouts/application'
然后在Site::BlogController
扩展Site::BaseController
我layout 'site/blog'
和/layouts/site/blog.html.haml
我
=content_for :header do
%h1 HELLO WORLD!
= render :file => 'layouts/site'
然后,这将按照问题中的描述呈现嵌套布局。很抱歉在我的问题中遗漏了这个。我应该仔细阅读。
答案 1 :(得分:7)
如果您创建这样的帮助器:
# renders a given haml block inside a layout
def inside_layout(layout = 'application', &block)
render :inline => capture_haml(&block), :layout => "layouts/#{layout}"
end
然后您可以像这样定义子布局:
= inside_layout do
# nested layout html here
= yield
这些布局可以像普通布局一样使用。
更多:http://www.requests.ch/blog/2013/10/30/combine-restful-rails-with-nested-layouts/
答案 2 :(得分:2)
我做过类似的事情,但只使用了1级子布局。可以轻松调整以允许多个级别。
在controllers / application_controller.rb中:
def sub_layout
nil
end
在控制器中(例如blog_controller.rb):
def sub_layout
"blog"
end
在layouts / application.html.erb而不是<%=yield%>
:
<%= controller.sub_layout ? (render :partial => "/layouts/#{controller.sub_layout}") : yield %>
制作部分layouts/_blog.html.erb
:
...code
<%=yield%>
...code
重复其他控制器&amp;子布局。
编辑: 如果您需要在每个操作的基础上执行此操作:
def sub_layout
{
'index' => 'blog',
'new' => 'other_sub_layout',
'edit' => 'asdf'
}[action_name]
end
答案 3 :(得分:2)
我想最简单的方法是在嵌套布局的父级中添加这行代码:
((render "layouts/#{controller_name}" rescue nil)|| yield )
只需更改要渲染的下一个布局的路径目录,即可添加任意数量的嵌套布局。
注意:确保您的嵌套布局名为_layoutname.whatever,并且您的嵌套布局内部有 yield
答案 4 :(得分:0)
您可以创建一个带有yield的部分。
_my_sub_layout.html.erb:
<h3>I'm a sub layout and here's my content:</h3>
<%= yield %>
在其他一些视图中,甚至在您的主要布局中,application.html.erb将partial渲染为布局:
<%= render layout: 'my_sub_layout' do %>
<p>I'm the sub layout's content</p>
<% end %>