Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional include tag in Django

I've ran into very strange behavior of Django template system. I have a template file, namely test.html, which recursively includes itself:

{% include "test.html" %}

Of course, such template has no chance to be rendered, since there is no finishing condition. OK, let's try the following:

{% if test_false %}{% include "test.html" %}{% endif %},

where test_false is a variable passed to template and equal to False.

One expects that it just will not include anything, but it does:

RuntimeError at /test/
maximum recursion depth exceeded while calling a Python object

I don't get it. Include tag can take arguments from current context, so I doubt it is executed before any other part of the page. Then why does it ignore condition tag?

like image 947
Andrei Smolensky Avatar asked Jun 08 '12 13:06

Andrei Smolensky


2 Answers

Django has optimization that include templates that are given by constants at compilation.

Set name of template to variable and include it in that way:

{% include test_template %}

Django will not be able to use it's optimization and your code should work.

like image 88
Tomasz Wysocki Avatar answered Sep 30 '22 10:09

Tomasz Wysocki


Like Thomasz says, Django can only make this optimization if the path is defined as a constant string in the including template - like so:

{% include "test.html" %}

But I would rather not have to put the template path in the context from Python code.

So here is a slightly more self contained way of achieving the same result - wrap the include in a with:

{% with "test.html" as path %}
    {% include path %}
{% endwith %}
like image 33
thnee Avatar answered Sep 30 '22 10:09

thnee