# Nested List Tag Helper

**URL:** <https://www.ruby-forum.com/t/nested-list-tag-helper/89947>\
**Category:** Rails\
**Created:** [March 24, 2007, 3:53am UTC](https://www.ruby-forum.com/t/nested-list-tag-helper/89947 "2007-03-24T03:53:14Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![SBSBSB](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecccb3/32.png) [@SBSBSB](https://www.ruby-forum.com/u/SBSBSB)\
**Post date:** [March 24, 2007, 3:53am UTC](https://www.ruby-forum.com/t/nested-list-tag-helper/89947/1 "2007-03-24T03:53:14Z")

</div>

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](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):

1. first
2. first

  1. third

```
<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>

```

The writeup:  
[http://blog.labratz.net/articles/2007/3/23/back-from-the-abyss-a-helper-to-create-nested-lists](http://blog.labratz.net/articles/2007/3/23/back-from-the-abyss-a-helper-to-create-nested-lists)
