How to render nested ul list for ancestry tree view

落爺英雄遲暮 提交于 2019-12-08 02:53:52

问题


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>

回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/13578945/how-to-render-nested-ul-list-for-ancestry-tree-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!