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

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

问题描述

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

  {%includetest.html%} 

当然,这样的模板没有机会被渲染,因为没有完成条件。好的,我们来试试如下:

  {%if test_false%} {%includetest.html%} {%endif %},

其中 test_false 是一个变量传递给模板并等于 False



一个人期望它不会包含任何东西,但它是:

  / test / 
中的RuntimeError调用Python对象时,最大递减深度

我没有得到它。包含标签可以从当前上下文中获取参数,所以我怀疑它是在页面的任何其他部分之前执行的。那么为什么它忽略条件标签?

解决方案

Django具有包含由编译时常数给出的模板的优化。 >

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

  { %include test_template%} 

Django将无法使用它的优化,代码应该可以工作。 / p>

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?

解决方案

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.

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

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