Friday, October 10, 2008

Passing optional local variables to a partial

In verbose_index.html.erb i want to pass some additional parameters to the _thing.html.erb partial:
<% @things.each do |thing| %>
<%= render :partial => thing,
:locals => {:some_extra_stuff => some_extra_stuff} %>
<% end %>

in index.html.erb i do not want to pass any additional parameters to the _thing.html.erb partial:
<%= render :partial => things %>

when I hit verbose_index everything will work fine. but when I hit index, I'll see this error:
undefined local variable or method 'some_extra_stuff'
for #

to fix, in _thing.html.erb I add a check to see if the local variable is assigned:
<% unless local_assigns[:some_extra_stuff].nil? %>
<%= some_extra_stuff %>
<% end %>

No comments:

Post a Comment