Feature Tutorial

Making an Extended Layout Based-on an Existing Layout (Advanced)

In the example file we've seen previously, both the "Features List" page and the "Feature Detail" page have a promotion text block. To make sure every page in the features folder contains this block, we need a new layout for these pages. But, if we copy the content of our common layout, there will be more duplicated code. So, we'll solve this by using the render template method and content_for.

First, modify the common layout /_layout.html.erb, add this content_for block below the <%= render :partial => "main_menu" %>:

<% if content_for? :feature_slogan %>
    <%= yield :feature_slogan %>
<% end %>

Because we don't need to display anything by default, there's no need to write the "else" part.

Next, add a new layout file _layout.html.erb in the features folder. Page files use the closest layout file by default, so the page files in the features folder will use the new layout.

The content of /features/_layout.html.erb is:

<% content_for :feature_slogan do %>
    <div class="well">
        <h3><%= lorem_sentences 2 %></h3>
<% end %>
<%= render :template => "/_layout" %>

The code above makes a new layout based on our common layout. It uses <%= render :template => "/_layout" %> to assign the layout /_layout.html.erb for these pages to use. And the <% content_for :feature_slogan do %> part adds the promotion text block for every page which uses this layout. Switch to your browser and you'll see both the "Features List" page and the "Feature Detail" page now have a promotion text block.