Rails中每个控制器有2个以上的动态布局选项



在Rails中使用多个layout语句将引发错误。Rails忽略除最后一条layout语句之外的所有语句。

然而,我有一个复杂的布局系统,需要动态渲染标准应用程序布局之外的几个不同布局(控制器中的layout选项只允许一个替代布局,其余默认为app/layouts/application.html.erb(。我希望以下将是一个很好的替代品:

在这种情况下,我使用static_controller.rb来呈现以下静态内容页面(about.html.erb, contact.html.erb, careers.html.erb, help.html.erb, home.html.erb, landing.html.erb, legal.html.erb, and policies.html.erb(。

  1. landing.html.erb将有一个自定义的完整页面布局,没有页眉或页脚
  2. aboutcontacthomelegal将各自跟随";主";布局[app/views/layouts/main.html.erb]
  3. careershelppolicies将各自跟随";not_main";布局[app/views/layouts/not_main.html.erb]

我在目标controller:中需要类似的东西

class StaticController < ApplicationController
...
layout 'full', :only => [:landing]
%w[about contact home legal ].each do |static_page|
layout 'main'
end
%w[careers help policies].each do |static_page|
layout 'not_main'
end
...
def about
end
...
end #Closes the Static Controller

这将比在每个动作调用中设置布局更可取。然而,Rails继续忽略前面的布局语句,即使它们被封装在%w数组中。有什么想法可以让这样的东西发挥作用吗?

class StaticController < ApplicationController
layout 'full', only: [:landing]
layout 'main', only: [:about, :contact, :home, :legal]
layout  'not_main', only: [:careers, :help, :policies]
.....
end

这对我在Rails7:上有效

class StaticController < ApplicationController
layout :select_layout
private
def select_layout
"main" if %w[about contact home legal].include? action_name
"full" if %w[landing].include? action_name
# ...etc
end
end

最新更新