Is there a more recursive way to do this?
<p>I have the following code:</p>

<pre><code>{% if thing.parent.parent.parent.link %}
    &lt;a href="/y/{{ thing.parent.parent.parent.link }}"&gt;{{ thing.parent.parent.parent.name }}&lt;/a&gt;
{% endif %}

{% if thing.parent.parent.link %}
    &lt;a href="/y/{{ thing.parent.parent.link }}"&gt;{{ thing.parent.parent.name }}&lt;/a&gt;
{% endif %}

{% if thing.parent.link %}
    &lt;a href="/y/{{ thing.parent.link }}"&gt;{{ thing.parent.name }}&lt;/a&gt;
{% endif %}
</code></pre>

<p>The key thing that changes in this non-recursive code, is simply adding a .parent to the link/link text.</p>

<p>I need to do this 20 times in total, as you can see, it's quite ugly to repeat and quite repetitive. Is there a more recursive and nicer way of doing it using django's template framework?</p>

<p>Return a list in your context and then you can use an iterative approach:</p>

<pre><code>{% for parent in parents  %}
    &lt;a href="/y/{{ parent.link }}"&gt;{{ parent.name }}&lt;/a&gt;
{% endfor %}
</code></pre>

<p>Since nothing special has to be done if it is a child (as you mentioned, the only difference is link and name), you can just convert the things' parents to a list. I cannot give an exact method to do this without knowing more about your data structures, but maybe this will give you an idea:</p>

<pre><code> parents = []

 for thing in things:
     node = thing
     while hasattr(node, 'parent'):
         parents.append(node.parent)
         node = node.parent
</code></pre>

python django recursion django-templates