Achaius
Achaius

Reputation: 6124

How to render nested ul list for ancestry tree view

I want to render a structure shown below using content_tag where the collection is the ancestry object.

  <ul>
    <li>
       <a>Fruits</a>
     <ul>
       <li>
         <a>Apple</a>
        </li>
        <li>
            <a>Orange</a>
        </li>
      </ul>
     </li>
     <li>
        <a>Colours</a>
     </li>
   </ul>

Upvotes: 2

Views: 2968

Answers (2)

Guilherme Lundgren
Guilherme Lundgren

Reputation: 61

I believe it's the answer, community, please, edit and tweak this post if it's wrong.

Create a helper method like this

def nested_groups(groups)
   content_tag(:ul) do
      groups.map do |group, sub_groups|
         content_tag(:li, group.name +  nested_groups(sub_groups))
      end.join.html_safe
   end  
end

then, pass the ancestry object to the method in the view:

<%= nested_groups(@groups.arrange) %>

it will render the ul-list the right way.

Upvotes: 6

Fabian Winkler
Fabian Winkler

Reputation: 1480

The following code will produce a properly nested list. See W3schools for example.

At first create a helper:

module AttributeHelper
  def nested_attributes(attributes)
    content_tag :ul do
        attributes.each do |attribute|
            concat(content_tag(:li, attribute.name))
            if attribute.has_children? 
                concat(nested_attributes(attribute.children))
            end
        end
    end
  end
end

Then use the helper method in your view:

= nested_attributes(@attributes.roots)

Upvotes: 3

Related Questions