Different layout for the same controller

In some projects can happen that you have to use different graphic templates for different methods of the same controller. At first sight one would implement a solution that provides an explicit call to the desired layout within each action.

Something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

class PostController < ApplicationController
def index
[...]
:layout => 'standard'
end

def show
[...]
:layout => 'standard'
end

def new
[...]
:layout => 'admin'
end

def edit
[...]
:layout => 'admin'
end
end

But there is an easier and DRY way to implement the same solution. To select the layout to use Rails tries to find an action called “choose_layout”.

By defining our version of “choose_layout” we can trivially manage the choice of the layout as you can see in the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

class PostController < ApplicationController

layout :choose_layout

def index
[...]
end

def show
[...]
end

def new
[...]
end

def edit
[...]
end

private

def choose_layout
if [ 'new', 'edit' ].include? action_name
'admin'
else
'standard'
end
end
end

This action uses the Rails variable “action_name”, that contains the name of the current action, to decide which layout to load.
So if action_name is ‘new’ or ‘edit’ it will load the ‘admin‘ layout, but for any other action it will load the ‘standard‘ layout.