首页 > 其他 > 详细

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

时间:2020-03-05 10:02:13      阅读:120      评论:0      收藏:0      [点我收藏+]

在模板中使用自定义变量一般是采用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 %}

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

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

原文:https://www.cnblogs.com/djflask/p/12418149.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!