在django template中定义临时变量,并自定义操作:赋值、自增

定义临时变量:

{% with i=1 %}
{{i}}
{% endwith %}

定义对临时变量操作的tag


在templatetags中创建set_val.py

内容是

from django import template
import logging
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""

class VarAddOneNode(template.Node):

    def __init__(self, var_name):
        self.var_name = var_name

    def render(self, context):
        try:
            value = template.Variable(self.var_name).resolve(context)
            context[self.var_name] = str( int(value) + 1 )
        except template.VariableDoesNotExist:
            value = ""

        return u""

def set_var(parser, token):
    """
        {% set   =  %}
    """
    parts = token.split_contents()
    logging.info('len(parts)=' + str(len(parts)))
    if len(parts) == 2:
        content = parts[1]
        if content[len(content)-2 :len(content)] == '++':
            var_name = content[:len(content) - 2]
            return VarAddOneNode(var_name)
        else:
            return u""
    elif len(parts) == 4:
        return SetVarNode(parts[1], parts[3])
        # raise template.TemplateSyntaxError("'set' tag must be of the form:  {% set   =  %}")


register.tag('set', set_var)
然后在template中引入

{% load set_val %}

前端代码示例

 {% load set_val %}
    
商品尺码
{% with i=1 %}
	    {% set i = 2 %}

                {% for size in  size_list %}

                    
原名:{{ size.sizeName }}
名字:
{% set i++ %}
{% endfor %} {% endwith %}

 
  



你可能感兴趣的:(django,前端)