Conditional include tag in Django

萝らか妹 提交于 2019-12-10 15:07:30

问题


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?


回答1:


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.




回答2:


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 %}


来源:https://stackoverflow.com/questions/10950275/conditional-include-tag-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!