Django中的条件包含标记

And*_*sky 5 django django-templates

我遇到了Django模板系统非常奇怪的行为.我有一个模板文件,即test.html递归地包含自己:

{% include "test.html" %}
Run Code Online (Sandbox Code Playgroud)

当然,这样的模板没有机会被渲染,因为没有完成条件.好的,让我们尝试以下方法:

{% if test_false %}{% include "test.html" %}{% endif %},
Run Code Online (Sandbox Code Playgroud)

where test_false是传递给模板的变量,等于False.

人们期望它不会包含任何东西,但它确实:

RuntimeError at /test/
maximum recursion depth exceeded while calling a Python object
Run Code Online (Sandbox Code Playgroud)

我不明白.Include标签可以从当前上下文中获取参数,因此我怀疑它是否在页面的任何其他部分之前执行.那为什么忽略条件标签?

Tom*_*cki 6

Django的优化包括编译时由常量给出的模板.

将模板名称设置为变量并以这种方式包含它:

{% include test_template %}
Run Code Online (Sandbox Code Playgroud)

Django将无法使用它的优化,您的代码应该可以工作.