Hello list,
I’m trying to render a tree using the following helper function (added it to ApplicationHelper):
def display_tree_recursive(tree, parent_id)
ret = “
if node.parent_id == parent_id
ret += "<li style=\"list-style:none;\">"
ret += yield node
ret += display_tree_recursive(tree, [node.id](http://node.id)
) { |n| yield n }
ret += “”
end
end
ret += “
”
end
In my view, I’ve got the following Erb code:
<%=
display_tree_recursive(@categories,0) do |node|
if node.parent_id == 0
"<b>" + [node.name](http://node.name) + "</b>"
else
pos = 20 if node.parent_id == 0;
pos = node.parent_id+20 if node.parent_id != 0;
"<span style=\"position:relative;right:#{pos}p\">#{[node.name](http://node.name)}</span>"
end
end
%>
Of course I’m going nowhere with this logic and that’s why I’d like to know of an easy and effective way to render a tree hierachically, in a way that a child get more to the right than its parent. Is there any helper available for this?
Thanks.
Hi Marcelo
def list_tree(tree, level = 0, &block)
content = tree.children.inject '' do |mem, node|
mem + block[node, level] + list_tree(node, level + 1, &block)
end
content_tag :ul, content_tag(:li, content),
:class => "#{tree.class.name.tableize}_#{level}"
end
<%=
list_tree @tree do |node, level|
content_tag("h#{level}", node.name) + content_tag(:p, node.text)
end
%>
Regards
Florian
PS: untested...
Thanks Florian… actually I’ve used the following code and it is working nicely, I will try you code though and let you know how it worked 
def display_tree_recursive(tree, parent_id)
ret = “
if (node.parent_id == 0)
classe = "root_node"
else
classe = "sub_node"
end
ret += "<li class=\"#{classe}\">"
ret += "<span class=\"#{classe}\">"
ret += link_to [node.name
](http://node.name), {:controller => “documents”, :action => “list”, :id => node.id}
ret += display_tree_recursive(tree, node.id) { |n| yield n }
ret += "</span>"
ret += "</li>"
end
end
ret += “
”
end
The CSS’ classes used:
.root_node {
font-size:14px;
font-weight:bolder;
list-style:none;
}
.sub_node {
font-size:14px;
text-indent:0px;
left:15px;
font-weight:normal;
position:relative;
list-style-position:inherit;
}
Thanks!
Marcelo.