【问题标题】:how to dynamically build a tree structure如何动态构建树形结构
【发布时间】:2012-07-31 05:30:59
【问题描述】:

在我看来,我得到了所有页面

我得到了我所有的页面以及所有的孩子和子孩子。如何得到如下图的树形结构:

<% 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...

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    您正在尝试在视图中创建递归,这不仅复杂而且会使您的视图代码非常混乱。 一个干净的方法是定义一个递归生成输出的辅助函数。

    我没有具体的例子,但是你可以在this similar question的答案之一中查看一个

    【讨论】:

    • 在尝试之后..我得到了解决方案...我渲染了部分,然后又渲染了自己..例如
    【解决方案2】:

    在尝试之后..我得到了 解决方案...我渲染部分,然后渲染自己..例如_show_children.html.erb ..

        <% 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`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      • 2017-01-10
      相关资源
      最近更新 更多