问题
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