【问题标题】:Is there a more recursive way to do this?有没有更递归的方法来做到这一点?
【发布时间】:2017-02-17 02:25:30
【问题描述】:

我有以下代码:

{% if thing.parent.parent.parent.link %}
    <a href="/y/{{ thing.parent.parent.parent.link }}">{{ thing.parent.parent.parent.name }}</a>
{% endif %}

{% if thing.parent.parent.link %}
    <a href="/y/{{ thing.parent.parent.link }}">{{ thing.parent.parent.name }}</a>
{% endif %}

{% if thing.parent.link %}
    <a href="/y/{{ thing.parent.link }}">{{ thing.parent.name }}</a>
{% endif %}

在这个非递归代码中改变的关键是在链接/链接文本中添加一个 .parent。

我总共需要这样做 20 次,如您所见,重复非常难看而且非常重复。使用 django 的模板框架有没有更递归更好的方法?

【问题讨论】:

    标签: python django recursion django-templates


    【解决方案1】:

    在您的上下文中返回一个列表,然后您可以使用迭代方法:

    {% for parent in parents  %}
        <a href="/y/{{ parent.link }}">{{ parent.name }}</a>
    {% endfor %}
    

    因为如果它是一个孩子不需要做任何特别的事情(正如你提到的,唯一的区别是链接和名称),你可以将事物的父母转换为一个列表。在不了解您的数据结构的情况下,我无法给出确切的方法来执行此操作,但也许这会给您一个想法:

     parents = []
    
     for thing in things:
         node = thing
         while hasattr(node, 'parent'):
             parents.append(node.parent)
             node = node.parent
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-13
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      相关资源
      最近更新 更多