Ruby on rails 在rails中,是否可以动态加载类布局?
我需要消息在项目中有一个不同的布局,在rails中可以这样做吗Ruby on rails 在rails中,是否可以动态加载类布局?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我需要消息在项目中有一个不同的布局,在rails中可以这样做吗 Class Messages::New < @project? ProjectLayout : NormalLayout end #i treid this, don't work, since @project has not been initiated. 类消息::新建'show\u布局' 结束 结束 我在ApplicationController中的两分钱: before_action :layout_by_act
Class Messages::New < @project? ProjectLayout : NormalLayout
end #i treid this, don't work, since @project has not been initiated.
类消息::新建<@project?ProjectLayout:NormalLayout
结束#我强调了这一点,不起作用,因为@project尚未启动。
谢谢决定控制器中的布局,而不是模型。您的ProjectsController可以使用自己的ProjectLayout,MessagesController然后可以使用普通布局(如果您愿意)。您只能在控制器级别应用布局:
class MessagesController < ApplicationController
layout :project
end
class messages控制器
还有一个关于如何进行条件布局的示例,由于问题不清楚,您还可以使用“渲染”选项仅为一个操作设置布局
render :action => 'new', :layout => 'layoutname'
这可能对你有帮助
class MessagesController < ApplicationController
layout :get_layout
def get_layout
@project? ? 'ProjectLayout' : 'NormalLayout'
end
end
class messages控制器
您只能在控制器
级别和单个操作
级别应用rails布局
每个控制器的唯一布局
class MessagesController < ApplicationController
layout "admin"
def index
# logic
end
end
class MessagesController < ApplicationController
layout :dynamic_layout
def index
# logic
end
protected
def dynamic_layout
if current_user.admin?
"admin" # Show admin layout
else
"other_layout" # Show other_layout
end
end
end
#个人行动级别布局
如果要为每个动作显示不同的布局,可以这样做
class MessagesController < ApplicationController
layout :dynamic_layout
def index
# logic
render :action => 'index', :layout => 'index_layout'
end
def show
# logic
render :action => 'show', :layout => 'show_layout'
end
end
class messages控制器'index',:布局=>'index\u布局'
结束
def秀
#逻辑
呈现:操作=>'show',:布局=>'show\u布局'
结束
结束
我在ApplicationController中的两分钱:
before_action :layout_by_action
@@actions = %w(new edit create update index)
def layout_by_action
if @@actions.include? params[:action]
self.class.layout 'admin'
else
self.class.layout 'application'
end
end
您可以使用:
layout -> {
if something?
'my-layout'
else
'my-other-layout'
end
}