Forum: Ruby on Rails Nested List Tag Helper

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
9f173c578c2ff435a41d448e25d62870?d=identicon&s=25 SB (Guest)
on 2007-03-24 03:53
(Received via mailing list)
I've taken a useful snippet for creating lists from the blog below and
turned it into something that can create a nested list from an array
of arrays.  Thought I'd share it since some of you might find it
useful and I also wanted to know if anybody can improve it (in general
and also add the ability to use the "cycle helper" by passing it into
the helper).

Inspiration:
http://termos.vemod.net/list-helper-for-rails


Here's the code:


def html_list(type, elements, options = {})
  items = elements.map  do |element|
    if element.is_a?(Array)
      element = html_list(type, element, options)
    else
      content_tag("li", element)
    end
  end
  content_tag(type, items, options)
end

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

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

This uses recursion so you can pass it an array of arrays.

So, this:
<%= ul ["first", "first", ["second", ["third", "third", "third"],
"second", "second", ["third", "third", "third", ["fourth", "fourth",
"fourth"]]]] %>

Becomes this (properly nested):

<ol>
  <li>first</li>
  <li>first</li>
  <ol>
    <li>third</li>

    <ol>
      <li>second</li>
      <li>second</li>
      <li>second</li>
    </ol>

    <li>third</li>

    <li>third</li>

    <ol>
      <li>second</li>
      <li>second</li>
      <li>second</li>
    </ol>

  </ol>
</ol>

The writeup:
http://blog.labratz.net/articles/2007/3/23/back-fr...
This topic is locked and can not be replied to.