Skip to content

Instantly share code, notes, and snippets.

@manfe
Last active January 14, 2020 10:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save manfe/f9f47ad128cc599c703991c9862ee03f to your computer and use it in GitHub Desktop.
Save manfe/f9f47ad128cc599c703991c9862ee03f to your computer and use it in GitHub Desktop.
Rails Helper to build Hierachical HTML List
module TreeListHelper
# the collection need to be the root parents
def tree_list(collection)
content_tag(:ul) do
collection.each do |item|
if item.children.any?
concat(
content_tag(:li, id: item.id) do
concat(item.name)
concat(tree_list(item.children))
end
)
else
concat(content_tag(:li, item.name, id: item.id))
end
end
end
end
end
@manfe
Copy link
Author

manfe commented Apr 7, 2016

This code will generate the following structure:

 <ul>
  <li>Immigration
    <ul>
      <li>News &amp; Stories</li>
      <li>The Data</li>
    </ul>
  </li>
  <li>Student Loans
    <ul>
      <li>News &amp; Stories</li>
      <li>The Data</li>
    </ul>
  </li>
</ul>

@victorhazbun
Copy link

what if the collection is not the root parent?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment