check out my new blog at gmarik.info/blog

Thursday, September 27, 2007

rails: optional locals values in partials

As you may know, rails' partial is a proper way for producing reusable view chunks

But sometimes you may need the partial to look different depending on contetext( say partial "_post" is used in "posts_list" and "single_post" templates). No problems - rails gives you :locals option

.rhtml

<%= render :partial => 'post', :locals => {:look_different => true} %>

And then you can do in parial like
_post.rhtml

<% if look_different %>
<p>look different <p>
<% else %>
<p>look usual <p>
<% end %>

But it gets painful passing all the locals all the time...otherwise you'll get NameError for not passing partial's option

Solution: optional locals values


Core rails team solution


just use local_assigns[:key] to access your local variables :)
Like
_post.rhtml

<% if local_assigns[:look_different] %>
<p>look different <p>
<% else %>
<p>look usual <p>
<% end %>

from rails 1.2.3 sources
from ActionView::Base docs

Labels: , , , ,

0 Comments:

Post a Comment

<< Home