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 %}

這個形式設置自定義變量了.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM