Rails中的多级嵌套布局3
我有一个应用程序与全局应用程序布局文件application.html.haml
。 然后,我有多个“控制器堆栈”:用于我们的主站点,管理门户和我们的业务站点。 对于其中的每一个,控制器都在一个模块中,并且都从同一个BaseController
inheritance。 每个堆栈都有自己的布局文件。 在堆栈中,一些控制器也有布局文件。
我希望所有视图(除非另有说明)在嵌套布局的多个级别内呈现:application,“stack”,“controller”。
例如,对于Site::BlogController#show
action,我想要rails来渲染:
/site/blog/show.html.haml
里面的/layouts/site/blog.html.haml
里面的/layouts/site.html.haml
里面/layouts/application.html.haml
我很难理解如何将/layouts/site.html.haml
插入堆栈。 看起来好像是自动的,rails会在应用程序布局中的控制器布局内呈现动作,但是,我看不到如何将布局“插入”渲染堆栈。
任何帮助都非常感谢,但是,我已经阅读了所有的rails指南都无济于事,所以链接到http://guides.rubyonrails.org/layouts_and_rendering.html#using-nested-layouts并没有多大帮助。
我重读了我发布的链接( 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
中扩展了Site::BaseController
我有layout 'site/blog'
和/layouts/site/blog.html.haml
我有
=content_for :header do %h1 HELLO WORLD! = render :file => 'layouts/site'
然后,这将按照问题中的描述呈现嵌套布局。 很抱歉在我的问题中遗漏了这个。 我应该仔细阅读。
如果您创建这样的帮助:
# 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/
我做了类似的,但只使用了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
重复其他控制器和子布局。
编辑:如果您需要在每个操作的基础上执行此操作:
def sub_layout { 'index' => 'blog', 'new' => 'other_sub_layout', 'edit' => 'asdf' }[action_name] end
我想最简单的方法是在嵌套布局的父级中添加这行代码:
((render "layouts/#{controller_name}" rescue nil)|| yield )
您可以通过仅更改要呈现的下一个布局的路径目录来添加任意数量的嵌套布局。
注意 :确保您的嵌套布局名为_layoutname.whatever,并且您的嵌套布局内部有一个yield
您可以使用其中的yield创建部分。
_my_sub_layout.html.erb:
I'm a sub layout and here's my content:
<%= yield %>
在其他一些视图中,甚至在您的主要布局中,application.html.erb将partial渲染为布局:
<%= render layout: 'my_sub_layout' do %> I'm the sub layout's content
<% end %>