Easy way to render a tree

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 = “


    tree.each do |node|
    if node.parent_id == parent_id
    ret += “<li style=“list-style:none;”>”
    ret += yield node
    ret += display_tree_recursive(tree, 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 + "</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
}"
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…