问题
In Rails 3 I use the following helper in order to get a even-odd-coloured table:
def bicolor_table(collection, classes = [], &block)
string = ""
even = 0
for item in collection
string << content_tag(:tr, :class => (((even % 2 == 0) ? "even " : "odd ") + classes.join(" "))) do
yield(item)
end
even = 1 - even
end
return string
end
And I use it in my views like this:
<%= bicolor_table(services) do |service| %>
<td><%= image_tag service.area.small_image %></td>
<td><%= link_to service.title, service %></td>
<% end %>
Now, I have to migrate the application to Rails 2. The problem is Rails 2 doesn't use Erubis, so when it finds a <%= whatever %> tag, it just calls whatever.to_s. So, in my case, this result in trying to execute
(bicolor_table(services) do |service|).to_s
With the obvious (bad) consequences. The question is: am I wrong in principle (like "helpers shouldn't work this way, use instead …") or should I look for a workaround?
Thanks.
回答1:
This is totally doable, and in fact makes certain types of helpers much simpler. You need to use <% %>
and concat
to achieve this.
def my_block_helper(param, &block)
output = %(<div class="wrapper-markup">#{ capture(&block) }</div>)
concat output
end
use it in your views like this:
<% my_block_helper do %>
<span>Some Content</span>
<% end %>
回答2:
This might not answer your question, but there is a much simpler way to achieve even/odd color table, using the cycle
command
@items = [1,2,3,4]
<table>
<% @items.each do |item| %>
<tr class="<%= cycle("even", "odd") -%>">
<td>item</td>
</tr>
<% end %>
</table>
Hope this at introduces you to a cool Rails utility
来源:https://stackoverflow.com/questions/3630854/converting-rails-3-to-rails-2-helpers-with-blocks