[LRUG] Funny gotcha with blocks in partials.
Chris Mear
chrismear at gmail.com
Mon Jun 22 09:08:00 PDT 2009
On 22 Jun 2009, at 16:31, Tim Cowlishaw wrote:
> However, if i pass it a block that contains ERB template strings, it
> breaks - it just returns the result of each call to the block direct
> to the template being rendered, as it's executed, rather than
> returning it as the result of the call to array_to_list itself:
>
> <% array_to_list(@flash_games, :class => "flash_games_grid") do |
> game, array| %>
> <a href="<%= game_path(:id => game.id) %>"><img src="<%=
> game.image_url(:grid) %>" alt="A Game" width="128" height="128" /></a>
> <% end %>
>
> I have a suspicion that this is something the rails capture() method
> might be needed for, but i'm struggling to understand how, Anyone
> seen anything similar in the past?
Yeah, I've done something like this before, by building up the output
using the concat method, and using capture to get the rendered results
of blocks defined in the ERB template. Something like this should work:
def array_to_list(data, opts={}, array=nil, &block)
array ||= data #pass the top level data structure down the stack.
if data.is_a?(Array)
concat('<ul>')
data.each do |e|
concat('<li>')
array_to_list(e, opts, array, &block)
concat('</li>')
end
concat('</ul>')
else
concat(block ? capture(data, array, &block) : data.to_s)
end
end
Making this less ugly-as-sin is left as an exercise to the reader.
Chris
More information about the Chat
mailing list