Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在rails中,是否可以动态加载类布局?_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on 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

我需要消息在项目中有一个不同的布局,在rails中可以这样做吗

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
  }