Cleaner views with content_for

August 5th, 2010

Episode #8 is all about content_for.  But isn’t content_for deprecated?  ….What?  ….Who said that?

Actually, what’s been deprecated is using an instance variable when accessing a content_for block. For example:

@content_for_#{name_of_the_content_block}

Don’t do that. Do it Ryan’s way.

In fact, the Rails API has some excellent documentation on content_for.

In passing, Ryan mentions that content_for can be used to create dynamic sidebars.  Err, the weblog of PJ Hyett and Chris Wanstrath go into much more detail in an old post Content for Whom?  Check it out. Good stuff.

Important to remember:

One caveat here is that content_for appends content. It don’t replace it.

Content_for is ignored in caches. So you shouldn’t use it for elements that will be fragment cached.

Since this railscast is an old one, I went looking around to see if this caching problem had been resolved somehow.  Best I could find was this solution from Idle Hacking. Hm.

I really, really like content_for. And I don’t think people use this enough. Instead I’ve been guilty of using if statements in my views… if this, render that, else render this… It can get pretty yucky.  But that caching bit has me concerned.

Entry Filed under: Professional,Railscasts Project,Ruby on Rails

3 Comments Add your own

  • 1. Ben Orenstein  |  August 6th, 2010 at 11:31 am

    Diggin this thing you got going on here!

    I’d learned about content_for a ways back, but had forgotten. Thanks for the refresher!

  • 2. lianaleahy  |  August 6th, 2010 at 11:48 am

    Thanks, Ben!

  • 3. Todd  |  August 7th, 2010 at 4:37 pm

    Hey, I wrote that hack on idle hacking for content_for. It’d definitely not perfect but i am using it for 3 of my rails sites. There are definitely edges that my hack will break in and I haven’t even thought about how it will upgrade to rails 3.x

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Pages

RSS Tweets

RSS Berkman Gender & Tech

Links

Tags

Meta