Nested layouts i RoR

Standard

There are several ways to render different layouts for parts of the app. Here I list a few examples.

ProjectsController & PeopleController:

layout :current_layout

def current_layout
  if @company && @company.persisted? && request.path_parameters[:action] == "index" # i prefer helper 'current_action'
    "company"
  else
    "application"
  end
end

Helper:

def parent_layout(layout)
  @view_flow.set(:layout, self.output_buffer)
  self.output_buffer = render(:file => "layouts/#{layout}")
end

Company layout:

#views/layouts/company.html.erb

<h1><%= @company %></h1>
<ul class="tabs">
 <li>Info</li>
 <li>Info</li>
 <li>Info</li>
</ul>
<%= yield %>
<%= parent_layout(:application) %>

People template:

# views/people/index.html.erb

<% if current_layout == "company" %> # just table
  <%= render "people_table" %>
<% else %>
  <h1>People controller</h3>
  <%= render @people %>
<% end %>

Projects template:

# views/projects/index.html.erb

<% if current_layout == "company" %> # just table
  <%= render "projects_table" %>
<% else %>
  <h1>Projects controller</h3>
  <%= render @projects %>
<% end %>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s