Snippet List
This template tag was inspired by http://djangosnippets.org/snippets/592/, but with improvements in the syntax it is used with to be more function-like, and avoiding the problem of conditional recursion as noted in http://djangosnippets.org/comments/cr/15/592/#c2472.
The syntax for using it can be seen in the docstring of the defrecurse() function. Additionally, a magic "level" variable is used to indicate the level of recursion, starting with 0 for the outermost level.
This should theoretically allow for nested recursion, but the inner {% recurse %} call cannot call the outer {% defrecurse %} block.
- template
- templatetag
- recursion
When you have a model containing a field that is a foreign key back to the same model, you could find yourself with a hierarchy with an infinite loop:
#Data modelling Back to the Future
> grandfather > father > son > father > ...
Using this field instead of the standard ForeignKey will ensure that no model instance is saved that has itself as an ancestor, breaking the relationship if it does.
(Enhancements: I am sure one would want to better enhance this with appropriate error handling instead of silently disconnecting the relationship. And the relevant forms ought not show ancestors in the field's widget to reduce the chances of this happening in the first place.)
- pre_save
- recursion
- loop
- foreign
[Original and further information available from here.](http://www.undefinedfire.com/articles/recursion-in-django-templates/)
**v1.1 Update (20/04/08):** Added the ability to recurse single elements as well as automatic skipping of empty elements.
Most of the tags are self explanatory, the only one that may cause confusion is the main `{% recurse %}` one. The format for this tag is `{% recurse [children] with [parent] as [child] %}` where “[children]” is the property that contains the children of the current element, “[parent]” is your starting element and “[child]” is the variable named used in the loop.
Example usage:
{% load recurse %}
... Headers and stuff ...
{% recurse category.category_set.all with categories as category %}
<ul>
{% loop %}
<li>
<h{{ level }}>{{ category.title }}</h{{ level }}>
{% child %}
</li>
{% endloop %}
</ul>
{% endrecurse %}
... The rest of the page ...
- template
- templatetag
- recursion
3 snippets posted so far.