Django-templatetags设置(在templates中使用自定义变量)

在模板中使用自定义变量一般是采用with的方法:

{% with a=1 %}
{{ a }}
{% endwith %}
// 但是这种方法有时候会有局限性, 例如不能设置为全局

这里需要使用自定义标签的方式:

{% load set_var  %}

{% set goodsNum = 0 %}

这只是个简单的写法,如果要使用自定义标签,首先要在settings中注册模板参数:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates')
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],

            'libraries': {
                'my_customer_tags': 'App.templatetags.set_var',
            }
        },
    },
]

然后在App文件夹下建立

templatetags
  __init__.py
  set_var.py

文件夹,set_var.py中写入

from django import template

register = template.Library()


class SetVarNode(template.Node):
    def __init__(self, var_name, var_value):
        self.var_name = var_name
        self.var_value = var_value

    def render(self, context):
        try:
            value = template.Variable(self.var_value).resolve(context)
        except template.VariableDoesNotExist:
            value = ""
        context[self.var_name] = value
        return u""


def set_var(parser, token):
    """
      {% set <var_name> = <var_value> %}
    """
    parts = token.split_contents()
    if len(parts) < 4:
        raise template.TemplateSyntaxError("'set' tag must be of the form: {% set <var_name> = <var_value> %}")
    return SetVarNode(parts[1], parts[3])


register.tag('set', set_var)

保存就可以使用

{% set a=1 %}

这个形式设置自定义变量了.

posted @ 2020-03-05 05:03  gavincc  阅读(1032)  评论(0编辑  收藏  举报