当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - Rendering Layout for specific actions

问题描述:

Here I've a controller with 4 actions and i wanna apply application layout ( the default layout ) to new action only , or in other words i wanna except only index action from the layout so i write this but it doesn't work, the index template is rendering with the layout.

class SessionsController < ApplicationController

layout 'application', :except => :index

def index

end

def new

end

def create

end

end

def destroy

end

end

also I tried

layout 'application', :only => :new

but it doesn't work too, same problem which the index template is rendering with layout.

any suggestions what's the problem here?

网友答案:

You can create a method to define your layout and fix your layout only on new action

layout :my_layout

def my_layout
  params[:action] == 'new' ? 'application' : nil
end
网友答案:

Here's code that you can use in your controllers:

layout :resolve_layout
...
...

private

def resolve_layout
  if %w(index show).include?(action_name)
    "application"
  elsif %w(show).include?(action_name)
    "admin"
  else
    "generic"
end

Basically, treat those arrays as your :only statements for layout that you are giving them if they are evaluated as true when compared with current action_name.

EDIT: I forgot to mention that this allows :only, :except, etc.

分享给朋友:
您可能感兴趣的文章:
随机阅读: