Skip to content
Generic recursion tags for Django templates
Find file
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.


Generic recursion tag for Django templates

Those are generic tags for representing recursive logic in django templates. The main usage is for displaying hierarchical data (trees).

Examples of usage.

In provided examples 'message' object is instance of the class:

class Message(models.Model):
    reply_to = models.ForeignKey('self', null=True, related_name='replies')
    subject = models.CharField(max_length=42, verbose_name=u'subject')
    closed = models.BooleanField(default=False)

Ex. 1: print message tree

{% load repeat_tag %}
{% repeat each message.replies for message %}
{{ message.subject }} {% repeat_here %}
{% endrepeat %}

Repetition will yield only for non empty (checked by len) sequences.

Ex. 2: If 'each' keyword is ommited, then 'repeat' tag would behave as list:

{% load repeat_tag %}
{% repeat message.reply_to for message %}
{{ message.subject }} {% repeat_here %}
{% endrepeat %}

In this case, repetition would stop on objects that evaluate to False.

Ex. 3: It's possible to make advanced render logic

{% load repeat_tag %}
{% repeat message.reply_to for message %}
{{ message.subject }} {% if not message.closed %} {% repeat_here %} {% endif %}
{% endrepeat %}


If 'repeat_here' is omitted inside 'repeat' tag, than the content would be rendered only once.

Usage of 'repeat_here' outside 'repeat' tag is considered as syntax error.

Theoretically it's possible to nest 'repeat' tags and also use 'repeat_here' tag multiple times in one enclosing 'repeat' tag. But those cases were not tested :).

Please be carefull with deeply nested structures: the implementation uses recursive calls and hence the max depth of Python interpreter stack can be exceed. This case is not handled.

Other approaches and implementations

Something went wrong with that request. Please try again.