zoukankan      html  css  js  c++  java
  • 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 %}

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

  • 相关阅读:
    [并发编程] 进程、线程
    100. 相同的树
    Python 问题集
    this关键字在函数中的应用
    去除列表右边框
    JS——作用域
    javascript——值传递!!
    null和undefined的区别?
    浏览器内核——四大主流
    http常用状态码
  • 原文地址:https://www.cnblogs.com/djflask/p/12418149.html
Copyright © 2011-2022 走看看