List Helper for Rails

Tired of writing <ul> and <li> all the time?

Here’s the cure in form of helper methods:

def html_list(type, elements, options = {})
  if elements.empty?
    "" 
  else
    lis = elements.map { |x| content_tag("li", x) }
    content_tag(type, lis, options)
  end
end

def ul(*args)
  html_list("ul", *args)
end

def ol(*args)
  html_list("ol", *args)
end

Example #1

<%= ul @pages.map(&:title) %>

…is the same as…

<ul>
  <% @pages.each do |x| %>
    <li><%= page.title %></li>
  <% end %>
</ul>

Example #2

ol %w(Foo Bar), :id => "foobar"

…returns…

<ol id="foobar">
  <li>Foo</li>
  <li>Bar</li>
</ol>

Credz

Thanks to Micah Wedemeyer for noticing that an <ul> element without <li> elements is invalid XHTML.

What about nested lists?

Sam sent this variant that handles nested lists. Cheers!