Setting different layouts for a controller based on a param

My webapp can be accessed in two different contexts. I want to be able to render the same view with two different layouts based on the context.

Is there a way to dynamically set the layout of the views based on the context? ie, if I have a param value which indicates the context type, can I change the layout dynamically?

Any help would be appreciated.

The classic (builtin) approach is to call

render :layout => ‘other_layout’

in your action.
I would also recommend considering my nested_layouts plugin ( to do it in your view, e.g.

class FooController < ApplicationController
layout ‘polymorphic’

before_filter :select_layout


def select_layout
if bar
@layout = ‘first’
@layout = ‘second’

module FooHelper
def polymorphic_layout



<% inside_layout polymorphic_layout do %>
<%= yield %>
<% end %>

That’s it. The advantage is that you don’t need to specify proper layout in every action.

Hope that helps.


That is a neat plugin. Very useful. Kudos and many thanks.

can’t find an answer in the agile rails book, but I think it is easy to
chain before_filters, so I can use multiple of these filters. Please
correct me if I am wrong.

Thanks again.

You can have as many filters as you want. They’re run in the order you call them. If you return false in any of them, the rest of the filters after that one will not run.

before_filter can be called in application.rb
and since all controllers inherit from that, you can leverage that to your advantage.

filters can apply to all actions

before_filter :do_some_stuff

Or some actions

before_filter :public_page_stuff, :only=>[:list, :show]

before_filter :admins_only, :except=>[:list, :show]

Yes, before and after filters are chained and, I believe, around filters are

Thanks Brian and Maxim.