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 |
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 |
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.