笔记:django自定义标签

from django import template
from django.template.base import Node, TemplateSyntaxError

register = template.Library()
'''
自定义标签
应用/templatetags/模块名.py
settings的INSTALLED_APPS中加上user.模块名
html模板中需要{% load 模块名%}
'''
class CalIndexNum(Node):
#计算视图列表中每行的序号
def __init__(self,numList):
self.numList = numList
def render(self, context):
realList = []
try:
for numobj in self.numList:
realList.append(numobj.resolve(context))
except:
raise TemplateSyntaxError("tag error")
try:
return int(realList[0])*(int(realList[1])-1)+int(realList[2])
except:
return ''
@register.tag(name="calindex")
def muladdNums(parser, token):
bits = token.contents.split()
realList = [parser.compile_filter(x) for x in bits[1:]]
return CalIndexNum(realList)


posted @ 2020-08-03 19:54  大牛等等我  阅读(177)  评论(0编辑  收藏  举报