django Framework Custom Template Tag of template tag Action Example

  • 2021-07-01 07:43:42
  • OfStack

This article illustrates the django Framework Custom Template Tag (template tag) operation. Share it for your reference, as follows:

django provides a wealth of template tags (template tag) and filters (tempalte filter), but these are not fully meet their own needs, so django also provides custom template tags and filter. Customizing these tags is actually very simple. For example, today there is a need to calculate the product of several numbers in the page, such as order quantity * order price * commodity discount.

Some people may say that you can calculate it first in view and then display it on the interface. Of course, this is ok. For more convenient, it can be calculated in view. If it is inconvenient, some data need to be combined and pieced together, which may not be convenient. So try to write the following tag for calculating the product:


#coding:utf-8
'''
Created on 2012-12-19
@author: yihaomen.com
 Calculate the product of multiple numbers 
'''
from django import template
from django.template.base import resolve_variable, Node, TemplateSyntaxError
register = template.Library()
class MulTag(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("multag error")
    try:
      value = realList[0]
      for num in realList[1:]:
        value = value* num
      return round(value,2)
    except:
      return ''
@register.tag(name="mymul")
def getMulNums(parser, token):
  bits = token.contents.split()
  realList = [parser.compile_filter(x) for x in bits[1:]]
  return MulTag(realList)

Basically, all django template tag are written in this way. It should be noted here that

1. In the getMulNums method parser.compile_filter This is very important.

2. In Multag numobj.resolve(context)

With the above methods, you can get the context content in the template correctly, otherwise you can only write dead content ( {%mymul 3 4 5 6%} This way)

For example, there are order and item in context of view view, and the object has the following calculation in template


{% load myMulTag %}
{%mymul order.num item.price item.discount%}

In this way, we can calculate the value, and no matter how many times we multiply, we can get the result.

Another point to pay attention to is their own template tag, 1 must be saved in the app under the templatetags directory. Otherwise, the load is not successful.

This way of writing django template tag is representative. Other tag can be written in a similar way. It can be written as the business rules you need, and the types of parameters you receive are different.

Reference: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

I hope this article is helpful to the Python programming based on Django framework.


Related articles: