gjb gjb - 7 months ago 51
Ruby Question

Rails helper method: Nested hash to nested HTML list

I am trying to write a Rails helper method to convert a nested hash into a nested HTML list.

For example:

{
:parent => "foo",
:children => [
{
:parent => "bar",
:children => [
{
:parent => "baz",
:children => []
}
]
}
]
}


should become:

<ul>
<li>foo</li>
<ul>
<li>bar</li>
<ul>
<li>baz</li>
</ul>
</ul>
</ul>


The hash may have any number of levels, and any number of parents per level.

What is the best way to achieve this please?

Answer

You can make a recursive method to render to hash to a nested set of lists. Place this in your relevant helper:

def hash_list_tag(hash)
  html = content_tag(:ul) {
    ul_contents = ""
    ul_contents << content_tag(:li, hash[:parent])
    hash[:children].each do |child|
      ul_contents << hash_list_tag(child)
    end

    ul_contents.html_safe
  }.html_safe
end