# Easy way to render a tree

**URL:** <https://www.ruby-forum.com/t/easy-way-to-render-a-tree/113333>\
**Category:** Rails\
**Created:** [August 29, 2007, 10:59pm UTC](https://www.ruby-forum.com/t/easy-way-to-render-a-tree/113333 "2007-08-29T22:59:22Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![mhfs](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/b2d939/32.png) [@mhfs](https://www.ruby-forum.com/u/mhfs)\
**Post date:** [August 29, 2007, 10:59pm UTC](https://www.ruby-forum.com/t/easy-way-to-render-a-tree/113333/1 "2007-08-29T22:59:22Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![mhfs](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/b2d939/32.png) [@mhfs](https://www.ruby-forum.com/u/mhfs)\
**Post date:** [August 30, 2007, 1:19am UTC](https://www.ruby-forum.com/t/easy-way-to-render-a-tree/113333/2 "2007-08-30T01:19:50Z")

</div>

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…
