This article mainly introduces you to the implementation method of using filter and simple_tag as the front-end custom function in Django. The article introduces it in detail through the example code, which has certain reference and learning value for everyone. Friends who need it can come and take a look below.
Preface
Django’s template engine provides general functional functions, and most codes can be implemented through the front end The logical function is called general here because it only supports function functions in most common situations, such as if judgment, ifequal comparison return value, etc., but slightly more complex functions are not supported, such as judgment through templates. Whether a return value is a legal numeric type, if we do not want to implement it through the background view code, we can customize some front-end functions.
Django provides us with two methods, namely filter and simple_tag. The following compares the two methods to implement the function function of judging the return value.
## 1. The application must be registered to settingsConfiguration file中
filter
Create a python module in the templatetags directory, named here app01_func.py, with the following content:from django import template from django.template.defaultfilters import stringfilter register = template.Library() @register.filter def value_verification(value): # value为前端传递的参数 try: int(value) return True except: return False
{% load app01_func %}
{% if load|value_verification %} {{ load }} is a valid int number. {% else %} {{ load }} is letter. {% endif %}
simple_tag
The coding method of simple_tag is the same as that of filter. The difference is that the simple_tag method needs to be called in the decorator partfrom django import template from django.template.defaultfilters import stringfilter register = template.Library() @register.simple # 这里修改为simple_tag def value_verification(value): # value为前端传递的参数 try: int(value) return True except: return False
{% value_verification load %}
{{ load | value_verification:"100"}}
def value_verification(value, custom): # 配置好形参 ...
{% value_verification load 100 200 ... %}
Comparison summary
Some things that the template engine cannot be done can be done through simple_tag and filter. Filter turns the function we specified into A method that returns an executable value. simple_tag changes the function function into a tag function, such as if, ifequal, etc. The calling method is also different. The comparison is as follows:##
{{ load | value_verification }} # filter {% value_verification load %} # simple_tag
The above is the detailed content of Detailed explanation of using filter and simple_tag to define functions for the front end in Django. For more information, please follow other related articles on the PHP Chinese website!