我得到了所有的页面以及所有的孩子和子孩子。如何获得如下所示的树结构:
<% for page in @pages%>
<li id="<%= page.id%>_page">
<div class="link">
#my attributes for the div<
/div>
#here I got the all siblings of that page. But here the structure is of just two
#levels. I need upto n-levels.
<% @childs = page.*descendants* %>
<% if !@childs.nil? && !@childs.empty? %>
<% for child in @childs%>
<ol class="child">
<li id="<%= child.id%>_page">
<div class="link">
#my attributes for the div
</div>
</li>
</ol>
<%end%>
<%end%>
</li>
<%end%>
page1
page 2
page 3
page 3.1
page 3.2
page3.4
...so on to last child
page 4
page 5
....so on to N-levels...
答案 0 :(得分:0)
您正在尝试在视图中创建递归,这不仅复杂,而且会使您的视图代码混乱不堪。 一种干净的方法是定义一个递归生成输出的辅助函数。
我没有任何具体的例子,但您可以在this similar question
的答案中查看其中一个答案 1 :(得分:0)
<% for page in @pages%>
<li id="<%= page.id%>_page">
<div class="link">
#my attributes for the div<
/div>
#here I got the all siblings of that page. But here the structure is of just two
#levels. I need upto n-levels.
<% @childs = page.descendants %>
<% if !@childs.nil? && !@childs.empty? %>
<% for child in @childs%>
<%= render :partial => "show_children", :locals => {:children => child`enter code here`.children }%>
<%end%>
<%end%>
</li>
<%end%>
.this partial will inturn render itself`