模板标签在if-sentence中没有按预期工作

时间:2014-10-21 14:53:29

标签: python django django-views django-templates

我制作了一个非常简单的模板标签,用于检查设置文件是用于生产还是开发。但似乎我不能使用if句子中的返回值?

我的标签:

from django.conf import settings

@register.simple_tag
def is_production():
    return settings.SETTINGS_MODE == 'Production'

在我的模板中:

{% if is_production %}
....
{% endif %}

当我打印变量{% is_production %}时,我的模板中返回True / False,但除此之外,它在我的if中不起作用。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

这是你必须做的:

而不是您的templatetag在templatetags / my_tag.py

中添加
from django import template

register = template.Library()

class IsProductionAreaNode(template.Node):
    def __init__(self, nodelist):
        self.nodelist = nodelist

    def render(self, context):
        if settings.SETTINGS_MODE == 'Production':
            return self.nodelist.render(context)
        else:
            return ''


def do_is_production(parser, token):
    nodelist = parser.parse(('endis_production',))
    parser.delete_first_token()
    return IsProductionAreaNode(nodelist)

register.tag('is_production', do_is_production)

现在,您可以在模板中执行以下操作:

{% load my_tag %}
.
.
.

{% is_production %}
    *content*
{% endis_production %}

答案 1 :(得分:0)

以下是一个常见的代码段:https://djangosnippets.org/snippets/1538/

但在你的情况下,我建议在视图中设置上下文变量is_production