Django 中的条件包含标签 [英] Conditional include tag in Django

查看:23
本文介绍了Django 中的条件包含标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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?

推荐答案

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

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 将无法使用它的优化,您的代码应该可以工作.

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

这篇关于Django 中的条件包含标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆