【问题标题】:show children nodes depending on selected parent根据选定的父节点显示子节点
【发布时间】:2011-05-17 21:37:58
【问题描述】:

您好,我一直在寻找,但找不到答案。我只有 3 个月的使用 python/django 的经验,所以请原谅我的虚拟问题! 我使用 django mptt 来显示一个简单的嵌套集导航。

<ul class="root">
{% recursetree nodes %}
    <li>
        {{ node.name }}
        {% if not node.is_leaf_node %}
            <ul class="children">
                {{ children }}
            </ul>
        {% endif %}
    </li>
{% endrecursetree %}

这很好用 - 但是我想只显示所选类别的子项(基于 slug)而不是全部。 有任何想法吗 ???


我终于做到了:

{% recursetree nodes %}
    <li>
      <a href='/{{ node.get_absolute_url}}'>{{ node.name }}</a>
    </li>
       {% if not node.is_leaf.node %}
                {% for c in child %}
                        {% if c in node.get_children  %}
                                {% if forloop.first %}
                                   <ul class="children">
                                         {{ children }}
                                            </ul>
                                {% endif %}
                        {% endif %}
                {% endfor %}
        {% endif %}   



{% endrecursetree %}          

在视图中

category = get_object_or_404(Category, slug=slug)
child = category.get_children()
if not child : 
      child = category.get_siblings() 

但这是一个黑客。有没有人有更好的主意?

【问题讨论】:

    标签: django django-mptt


    【解决方案1】:

    你需要发送一些关于你所在节点的信息,然后是一个简单的if 语句。

    关于如何通用地向下发送节点信息,在 Django 中有几种方法可以做到这一点,但没有一种是完美的。我首选的方法是上下文处理器:http://docs.djangoproject.com/en/1.3/ref/templates/api/#writing-your-own-context-processors

    【讨论】:

      【解决方案2】:
      {% recursetree nodes %}
        <li>
            <a href="/category/{{ node.get_absolute_url }}">{{ node.name }}</a>                           
             {% if node.name == category.name %}
               <ul>
                  {{ children }}
               </ul>
             {% endif %}
        <li>
      {% endrecursetree %}
      

      【讨论】:

        【解决方案3】:

        你可以试试这个:

        {% recursetree nodes %}
            #check if the node is a child node
            {% if node.is_child_node %}
                <a href="{{ node.get_absolute_url }}" >{{ node.name }}</a>
            {% endif %}
        
            #check if a root node is the current category
            {% if node.is_root_node and node.name == category.name %}
                {{ children }}
            {% endif %}
        
        {% endrecursetree %}
        

        【讨论】:

        • 如果您提供代码,请描述为什么此代码可能会解决问题。 “你可以试试这个:” 还不够。请edit您的回答。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多