cman77
cman77

Reputation: 1783

how to switch out rails layouts?

I'm fairly new to rails and am stuck on the concept of layouts.

My app is using Bootstrap grids. In my application.html.erb I have the following:

<div class="row">
 <div class="span8">
    <%= yield %>
 </div>

 <div class="span4">
    <%= render 'layouts/right_col'%>
 </div>
</div>

It's a basic main column with right hand narrow column layout. The majority of the app will have this layout.

But on few particular view actions - I want to have a full width column:

<div class="row">
<div class="span12">
   <%= yield %>
</div>
</div>

How should I organize my layouts to support this? And where would the override occur?

Thanks for the help!

Upvotes: 0

Views: 949

Answers (2)

Matthew
Matthew

Reputation: 13332

There are a few ways to do this. The easiest will be for you to simply create another layout file. For example create app/views/layouts/wide.html.erb that has your:

<div class="row">
<div class="span12">
   <%= yield %>
</div>
</div>

code in it. You can then selectively render with that layout from your controller method like this:

def show
  ...
  render :layout => :wide
end

Rails 3 also has a mechanism in place to set up a template hierarchy. This is a little more complex to set up, but it would probably lead to code that is more DRY. You can learn more about it in this railscast.

Upvotes: 2

Anthony Alberto
Anthony Alberto

Reputation: 10405

Two options for me :

1) You create two distinct layouts. If the only difference is the menu, then I wouldn't do that.

2) For the concerned actions that shouldn't display the menu, declare a variable, in the controller :

def some_action_with_no_side_menu

  @no_side_menu = 1
  #...
end

Then in the layout :

<% if defined? @no_side_menu %>
<div class="row">
  <div class="span12">
    <%= yield %>
  </div>
</div>
<% else %>
  <div class="row">
    <div class="span8">
     <%= yield %>
    </div>

    <div class="span4">
      <%= render 'layouts/right_col'%>
    </div>
  </div>
<% end %>

Upvotes: 2

Related Questions