Subscribe to RSS

Content_for, yield and making sure something gets displayed

You may have heard of a very nice Rails technique that used content_for and yield to stuff custom blocks of content into a layout. For example, in a view you could add a block like this:

<% content_for :sidebar do %>
  This goes into the sidebar when viewing this action!
<% end %>


It doesn’t matter where you put it in the view, because, as you may notice, the content within the content_for block is not shown in the view. The layout can pull the content for :sidebar and show it in a custom place, mostly the sidebar:

<%= yield :sidebar %>

Nice, you now don’t have to hard-code the sidebar (and it’s layout elements) in your views everytime. You can even move the sidebar to another place, without breaking any of your views. How great is that?

What does break your views, however, is not assigning anything to :sidebar. If you don’t assign anything to the :sidebar, nothing will be shown, which might break your layout. (Empty div’s tend to do that.)

So, how can you solve this? Quite easily, actually. What you want, probably, is display a default sidebar when no custom sidebar has been assigned. you can do this with the following line of über sexy Ruby code:

<%= (sidebar = yield :sidebar) ? sidebar : render(:partial => 'shared/sidebar') %>

First, you grab the :sidebar content and stuff it into a variable named, you guessed it, ’sidebar’. If this sidebar containts anything, show it. If it doesn’t, you render a partial in the app/views/shared directory named _sidebar.rhtml.

Well, there you are. Go enjoy yourself now.

Please share the love of this post by bookmarking it, and sharing it with others. Thanks!

  • Digg
  • del.icio.us
  • description
  • Reddit
  • Technorati
  • BlinkList
  • E-mail this story to a friend!
  • Facebook
  • Live
  • MisterWong
  • Netvouz
  • NewsVine
  • Slashdot
  • SphereIt

5 Comments

  1. Posted 3 October, 2007 at 09:07 | Permalink

    You can also use this to add a custom title to your pages for certain views. This is really a powerful feature.

  2. Posted 6 November, 2007 at 20:38 | Permalink

    Thank you for the great posts–keep them up! I tried to use this particular article but my content won’t render. I checked my logs and it says that it is rendering the shared partial, but when I refresh my browser, still no sign of the content. I have the appropriate code in the layout, view, and partial–am I missing something in the controller?

    Thanks!

  3. Posted 10 January, 2008 at 08:21 | Permalink

    ’shared/sidebar’) %>

    is better written

    ’shared/sidebar’) %>

    ueber-ueber sexy ruby code?

  4. Posted 10 January, 2008 at 08:27 | Permalink

    um.. meant


    <%= yield(:sidebar) || render(:partial => 'shared/sidebar') %>

    here

  5. wg
    Posted 3 July, 2008 at 20:55 | Permalink

    This is was very useful.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*