Content_for Sorta Nested Layouts

For my latest project, I needed to insert a small piece of code into all views belonging to a controller. At first, I had solved this by adding a partial to every view, but I thought it would be nice to DRY it up a little more and create some sort of nested layout within the main layout. This article by Matt McCray explained how I could easily achieve this by yielding within a partial, specified by a sub_layout method in the controller. The only disadvantage I found was that content_for constructions within the nested layout were not evaluated in this way, while the small piece of extra layout had its own css and javascript, too.

In order for content_for blocks to be evaluated, it needs to be yielded. The simple solution I therefore came up with was to yield the nested-layout-partial itself from a content_for defined in the main layout:

<% content_for :with_nested_layout, render(:partial=> "layouts/#{controller.sub_layout}") %>
<html>
 <head>
  <title>Nested layout example</title>
  <%= stylesheet_link_tag 'common', 'clearfix' %>
  <%= javascript_include_tag :all %>
  <%= yield :content_for_css %>
  <%= yield :content_for_js %>
 </head>
 <body>
  <div id="main" class="clearfix">
   <%= yield_flash_messages -%>
   <%= yield :with_nested_layout %>
  </div>
 </body>
</html>

This way, I can specify content_for :content_for_css and :content_for_js in the nested layout, which are evaluated because the partial itself is yielded, too. Of course this can be considered as a ‘dirty hack’, and I do agree to some extent, but it’s only two lines of code and it works like a charm, so I forgave myself for implementing it this way :)

About these ads

~ by moiristo on August 16, 2008.

2 Responses to “Content_for Sorta Nested Layouts”

  1. Is this still a good way to do it? I noticed this post is a few months old, so i was *hoping* that rails has put something in core to solve this problem.

  2. I am not aware of new possibilities regarding this topic.. if you find out, please let me know :)

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

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: