views:

297

answers:

2

I have the need to display a nested set structure in HTML. I am doing it with the following partial:

<ul<%= ' id="tree"' if depth == 0 %>>
<% items.each do |item| %>
  <li id="node_<%= item.id %>"><a><%= item.name %></a>
  <% if item.has_children? %>
    <%= render :partial => 'tree_level', :locals => {:items => item.children, :depth => depth + 1} %>
  <% end %>
  </li>
<% end %>   
</ul>

Is this the best place to have the code? I "feel" like there should be a to_html method on the object which dumps the entire tree structure for me, though this works.

+1  A: 

I am not sure whether it is best practice but I used similar code for rendering project tree.

Faster alternative is to create helper method doing the same job (recursively traversing tree and adding partial strings into result string). It is a little bit PHP style :( but for such a small amount of HTML is it OK, I guess :)

Helper looks like:

def render_node(node)
  res = "<ul>"
  ...
  node.items.each {|n| res << render_node(n)}
  ...
  res << "</ul>"
  res
end

Then it is used like this:

<%=render_node ProjectTree.new%>
Jarek
A: 

Well, you should realize there's a (small) overhead for using partials, so if performance is an issue, you may not want to use them this much. Otherwise I see little problem with using this.

However, you might want to use the collection-variant of partials (see "Rendering a collection of partials" on this API page, it could clean up your code a bit.

Jeroen Heijmans