a. Create templatetags module in app (required)
b. Create a .py file in templatetags, such as my_tags.py
from django import template from django.utils.safestring import mark_safe register = template.Library() # The name of the register is fixed and cannot be changed @register.filter def filter_multi(v1,v2): return v1 * v2 @register.simple_tag def simple_tag_multi(v1,v2): return v1 * v2 @register.simple_tag def my_input(id,arg): result = "<input type='text' id='%s' class='%s' />" %(id,arg,) return mark_safe(result)
c. Import the previously created my_tags.py in html: {% load my_tags%}
d. Use filter and simple_tags (how to call)
-------------------------------.html
{% load xxx %} #First line
# num=12
{{ num|filter_multi:2 }} #24 The maximum number of parameters is 2, but they can be placed in the if for statement
{{ num|filter_multi:"[22,333,4444]" }}
{% simple_tag_multi 2 5 %} The parameters are not limited, but they cannot be placed in the if for statement
{% simple_tag_multi num 5 %}
e. Configure the current app in INSTALLED_APPS in settings, otherwise django cannot find the custom simple_tag
Note: (filter can be placed in an if for statement, simple_tags cannot)
{% if num|filter_multi:30 > 100 %}
{{ num|filter_multi:30 }}
{% endif %}