Using blocks in views

Out of curiosity, why is it that the following doesn’t work in a view:

<%= @items.each { |@item| render :partial => ‘itemrow’ } %>

of course it’s easily achieved like this:

<% for @item in @items %>
<%= render :partial => ‘itemrow’ %>
<% end %>

Is it just not possible to use blocks in a view?

François Montel wrote:

Out of curiosity, why is it that the following doesn’t work in a view:

<%= @items.each { |@item| render :partial => ‘itemrow’ } %>

of course it’s easily achieved like this:

<% for @item in @items %>
<%= render :partial => ‘itemrow’ %>
<% end %>

Is it just not possible to use blocks in a view?

I’m not sure why one works and one doesn’t, but neither is the easiest
way to do what you are trying to do. The easiest way to do this is using
the :collection parm of the render call.

<%= render :partial => ‘itemrow’, :collection => @items %>

This will iterate over the collection and render the partial once for
each item in the collection. Each time the partial is rendered, the
current item from the collection is mapped into a variable that matches
the name of the partial.

So, in this case, inside your _itemrow.rhtml partial, the variable
“itemrow” (no ‘@’ sign) will reference the current item from the
collection. For instance, let’s say your @items consists of an array of
objects with name and price attributes - then your _itemrow.rhtml
partial might look something like this:

<%= itemrow.name %> <%= itemrow.price %>

c.

On Sat, Nov 18, 2006 at 08:28:27AM -0800, zero halo wrote:
}
} Out of curiosity, why is it that the following doesn’t work in a view:
}
} <%= @items.each { |@item| render :partial => ‘itemrow’ } %>
}
} of course it’s easily achieved like this:
}
} <% for @item in @items %>
} <%= render :partial => ‘itemrow’ %>
} <% end %>
}
} Is it just not possible to use blocks in a view?

You would need to use inject rather than each because render :partial
returns the rendered HTML as a string and you are returning @items from
each. That aside, though, the right way to render a partial on a
collection
is:

<%= render :partial => ‘itemrow’, :collection => @items %>

Rails does the loop for you.

–Greg

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs