mattmccray

 
« Comatose 0.8 Released… | Home | Comatose 0.8.1 »

Sorta Nested Layouts

» Published February 19, 2007 under Rails, Software

I was playing around with layouts in Rails the other day… I know, clearly I have too much time on my hands. But anyway, I found that you can fake a nested layout scheme in Rails by delegating view rendering to partials. As an added bonus, you don’t need to hack around with any of Rails’ internals to make it work.

For example, let’s say I’m working on an application that has both a public layout and an admin layout. The public layout consists of tabs and a sidebar. The admin layout has different tabs and no sidebar at all. Both layouts share a site header graphic.

With that in mind, here’s how we could structure our layouts and partials:

app/views/layouts/application.rhtml

<html>
  <head>
    <title>Layout Example</title>
  </head>
  <body>
    <div id="header"><!-- shared header code --></div>

      <%= render :partial=>"layouts/#{controller.sub_layout}" %>

    <div id="footer><!-- shared footer code --></div>
  </body>
</html>

Note: I’m getting the partial name from a controller method named sub_layout. I’ll explain that bit in just minute—In the meantime, knowing that it’ll return either ‘public’ or ‘admin’ is enough.

You’ll notice I don’t have a call to <%= yield %> in the layout itself…

So then, your partials (or sub layouts) will look something like this:

app/views/layouts/_public.rhtml

<div id="tabs"><!-- public tabset --></div>
<div id="public-content">
  <div id="sidebar">
    <!-- sidebar content here -->
  </div>
  <%= yield %>
</div>

app/views/layouts/_admin.rhtml

<div id="tabs"><!-- admin tabset --></div>
<div id="admin-content">
  <%= yield %>
</div>

Ah, there’s the <%= yield %>! That’s how you can delegate the view rendering. Basically, you’re using a partial to wrap HTML around the call to <%= yield %>.

OK, in the application.rhtml listing above, I get the partial that works as a sub layout from the controller. To hook that up, in your ApplicationController, you can specify a default sub layout like this:

class ApplicationController < BaseController

  # .. your actions

  def sub_layout
    "public" 
  end

end

Then in any administrative controllers, you can override it:

class UsersController < ApplicationController

  # .. your admin-like actions

  def sub_layout
    "admin" 
  end

end

I went ahead a threw together a little example application to better illustrate:

Perhaps the example of different tabs and sidebars isn’t most compelling reason to use sub layouts—Which is fine. The key point to all of this is that you can delegate the rendering of your view from a layout to a partial. Which I’m sure you can leverage in all kinds of cool ways…


127 comments

02.19.07 @ 18:41 Aaron Pfeifer said...
There’s a plugin I often used to achieve nested layouts: http://nested-layouts.rubyforge.org/
08.02.07 @ 14:37 Chirag Patel said...
Thanks Matt for writing this up in such a clear and detailed way! I will be using your method rather than using the nested-layouts plugin. Your method is pretty simple to understand. Second, I prefer using proprietary plugins only when they save significant amounts of time. I may be wrong in this case, but I believe having full control using what’s out of the Rails box, will allow easier maintainability if the app grows and more Rails programmers are needed.
06.20.08 @ 04:18 Asyraf said...
Hey matt,

Thanks for the tip – using partials instead of a plugin is way simpler and ‘update-proof’.

I used “layouts/#{controller.controller_name}” in my render method instead of defining a new method in my controllers.

wrote about it in my blog, rubynerds.blogspot.com under “nested layouts for Rails”. check it out!
12.31.08 @ 00:11 Jacques said...
Very cool. Exactly what I was looking for. Thanks bro!
03.22.09 @ 02:06 prash said...
thanks! this worked very well for me.

several (but not all) of my views required a standard header and footer (separate from the overall site’s header and footer) – a prime candidate for nested layouts.

the sub_layout technique worked out very well …
07.20.09 @ 23:26 Brian Armstrong said...
Nice solution! Cleanest one I’ve seen, thanks for posting it.
04.08.10 @ 20:24 Nate said...
Thanks for this! I love how clean it is. I modified it slightly by checking to see if the controller responds to the sub_layout method first. My layout looks like this now (I use haml):

– if controller.respond_to?(‘sub_layout’)
  = render :partial => “layouts/#{controller.sub_layout}”
-else
  = yield
04.22.10 @ 07:30 Rohan Dey said...
Exactly matching to my needs…...Thanks
03.02.11 @ 23:14 JC Grubbs said...
I find it’s helpful to stick the sub_layout() method in a helper and if you call the clear_helpers() method in the controller the sub_layout() method will only be available to the current controller. I think it’s cleaner to not have this kind of view/render related logic in the controller. But the idea is the same…thanks for the insight.
06.08.11 @ 03:56 Barefoot Shoes said...
I cannot seem to find the answer anywhere. Also what with there being no archive for July I’m guessing that her schedule got so tight that she has had to put her talents to other worthwhile endeavours.
07.07.11 @ 02:37 Oakley Sunglasses said...
Thank you for sharing,this information is useful to me.good quality
07.08.11 @ 23:49 iphone case said...
Excellent article~!Wel done!
07.08.11 @ 23:50 Brian Atwood said...
My pleasure~!
07.08.11 @ 23:51 Air Max 90 said...
I have never read such a wonderful article and I am coming back tomorrow to continue reading.
07.08.11 @ 23:51 Nike pas cher said...
o be more valuable way to gain traffic and of course get backlink.
07.08.11 @ 23:52 ED Hardy Clothing said...
interesting, hopefully you will keep posting such blogs….Keep sharing
07.08.11 @ 23:53 Shox pas cher said...
looks like fun buddy, wish bw would have said something about the snap on party, im not too far away.
07.12.11 @ 10:02 leely said...
I definitely recognize that the critical information supplied is connected to each of us . Thanks .
Bridgeport locksmiths
07.12.11 @ 13:08 piply said...
Locksmith Norwalk CT
Locksmith San Leandro CA
Locksmith Memphis
07.12.11 @ 13:11 hamerlue56 said...
Great task ! Your web page has presented me much of the material I requested .
locksmith coral springs fl
Fremont locksmith
fort worth locksmith
07.12.11 @ 13:12 hamerlue56 said...
Top class services; I will surely come back to your site for additional knowledge.
[url http://www.ProBerkeleyLocksmith.com]Lock..Locksmith Berkeley CA[/url]
[url http://www.MilpitasLocksmith.com]Milpita..Milpitas locksmith[/url]
[url http://lewis77shelton1.webs.com/apps/blo..locksmiths fort worth[/url]
07.20.11 @ 03:03 Nike Air Shoes said...
Foot wears are actually noticeable Jordan Shoes plus they express the kind of choice you possess. Air Jordan is really a popular class of waders which was very first noticed about the board in 1985. The loan of introducing these good quality boots would go to Nike the industry well-known and reputable name. A large number of fans prefer wearing Nike’s Air Jordan which is not just easy to wear but stylish too. Nike Air Shoes Let us reveal some other wonderful facts about these foot wears! The easiest approach of locating these shoes is you start your search with your nearby foot wear supermarkets and shops. It provides you with an idea about prices of various types of waders so, you can like the one which suits your decision and is Air Jordan Shoes inexpensive too.
07.22.11 @ 01:57 Air Jordan Shoes said...
Nike air jordan shoes haven’t only dominated the sports and especially the Basketball, Nike Air Shoes however they also provide been included in the background music world; for instance it’s not anything a new comer to see pop music celebrities adorning the shoe. Fashion followers too haven’t been left out.There are a number of varied moment’s celebrities, athletes, and popular music artists and bands result wearing Air Jordan shoes. As an example Jordan ShoesBrand have produced new brands of Nike air jordan shoes created specifically for the hiphop music videos which were like a form of item placement. You’ll be amazed at how common Nike air jordan footwear is and the way many Air Jordan Shoesmovies and rap artists use them in Hollywood.
07.25.11 @ 19:06 Coach Outlet said...
Glad to visiting your blog,it’s nice and usefull,thank you!
07.25.11 @ 19:32 cheap clothes said...
many people like to wholesale designer clothing and cheap clothes online. fashion clothing stores supplies really cheap designer clothes here.
07.25.11 @ 19:33 discount mac cosmetics said...
you may like the cheap mac makeup, it sounds well. they like to wholesale mac cosmetics here. discount mac makeup at mac cosmetics outlet online.
07.26.11 @ 02:28 cherry said...
I think this a good blog post,thanks for sharing.
07.27.11 @ 01:47 Nike air max said...
designer t shirts

t-shirts for men
07.29.11 @ 19:33 cheap jordan sneakers said...
Great post, thank you very much, please write more and more about this. Very interesting.d and understand.,sdadasd
07.30.11 @ 03:59 coach outlet online said...
he coach factory outlet is tightened via a leather rope and a clip Coach Handbags 2011 front closure. coach wallets With its double 19
07.30.11 @ 05:09 cheap leather messenger bags for women said...
Great blog, just looking around some blogs, seems a pretty nice platform you are using. I’m currently using Wordpress for a few of my sites but looking to change one of them over to a platform similar to yours as a trial run. Anything in particular you would recommend about it?
07.30.11 @ 23:17 coach outlet said...
Great blog, just looking around some blogs, seems a pretty nice platform you are using. I’m currently using Wordpress for a few of my sites but looking to change one of them over to a platform similar to yours as a trial run. Anything in particular you would recommend about it?
08.01.11 @ 00:46 Nike Outlets said...
Thank you for your article to share with us,Where can you buy cheap shoes? at the heel which is arresting from the ancillary of the in Air Max Premium a lot of models.
08.01.11 @ 20:21 Ghd Australia said...
This wonderful product is simply the best because it liberates vast amount of far infrared heat; that distributes eventually on the whole surface and that will keep your locks safe and full of moisture. Also protect them from any spot damages. It also produces the right quantity of negative ions. These are really effective in order to stop the unneeded chemical; bacteria and fungi etc.Its automatic heat control system not only gives you the heat control setting to set it according to your need. But if it is not being used for more than 30 minutes, automatically its heater will turn off which makes it light when it comes on power-consumption. GHD Hair Straightener has the ability to control its own internal temperature. To avoid internal condensation, the straightener turns-off itself when the temperature of the room falls below 8 degree Celsius.So what you are waiting for? The best electronic products are currently available in the market grab it up with GHD IV Salon Styler Ceramic or GHD IV Styler Ceramic Hair Straightener. You got it?
08.01.11 @ 21:18 Ray Ban sunglasses said...
Very useful article i wll add this into my blog,Cheap Oakley Sunglasses well done my friend
08.02.11 @ 18:51 UGG said...
I have read a number of the articles on your blog currently. And I like the way you write. I added your blog to my favorites blog site list and definitely will be returning soon. Please check out my own blog as well and tell me what you think.
08.03.11 @ 02:43 Discount Air Jordans said...
All good things come to an end.
08.03.11 @ 07:15 Nike vapor soccer shoes said...
The next generation Vapor boots have arrived and are one of the most unique yet. Unsuprisingly, the new Superfly III boots have been dominating the headlines, but now it’s time to take a look at the boot that paved the way for the Mercurial Superfly – the original Nike Speed boot!
08.03.11 @ 21:46 Fendi Sunglasses said...
Great trees are good for nothing but shade.

One or more comments are waiting for approval by an editor.


No trackbacks

Trackback link:

Please enable javascript to generate a trackback url


You may use Textile, or simple html tags (B,I). Feel free to use Emoticons too. Oh, and please limit yourself to only five links per comment. Anything more and you'll probably get detained by the spam police.