问题描述:

Let's say I want to create an HTML list helper that would allow me to loop through a collection, and only output the <ul> or <ol> tags if there are any list items (what I actually have in mind is a bit nastier, but this'll work for an example).

Something like:

<% html_list(:ul, MyModel.all) do |my_model| %>

<span><%= my_model.id %></span>

<% end %>

(As you can tell, I'm lost.)

I cannot wrap my head around what would go in my html_list method. Would you mind pointing me in the right direction?

网友答案:

You'd probably want something like this:

def html_list(tag, enum)
    html = '<' + tag.to_s + '><li>'
    html << enum.map { |e| yield e }.join('</li><li>')
    html << '</li></' + tag.to_s + '>'
    html.html_safe
end

or perhaps this way:

def html_list(tag, enum)
    html = [
        '<' + tag.to_s + '>',
        '<li>',
        enum.map { |e| yield e }.join('</li><li>'),
        '</li>',
        '</' + tag.to_s + '>'
    ]
    html.join.html_safe
end

There are various ways to build the final string, the meat of it is that you're building a method that takes a block and iterates over an enumerable and applies the block to each element along the way.

相关阅读:
Top