This article mainly introduces examples of Custom template tags in the Python Django framework. tags are more useful than filters. For more information about how to customize a template tag, see, you need to tell Django how to perform this process when encountering your tag.
When Django compiles a template, it divides the original template into nodes. Each Node is an instance of django. template. Node and has the render () method. Therefore, a compiled template is a list of node objects. For example, look at this template:
Hello, {person. name }}. {% ifequal name. birthday today %} Happy birthday! {% Else %} Be sure to come back on your birthday for a splendid surprise message. {% endifequal %}
The compiled template is in the form of a node list:
- Text node: "Hello ,"
- Variable node: person. name
- Text node: ". \ n"
- IfEqual node: name. birthday And today
When you call the render () method of a compiled template, the template uses the given context to call the render () method of each node on its node list. These rendering results are combined to form the template output. Therefore, to customize template labels, You need to specify how the original template labels are converted into functions completed by the node (compile function) and node render () methods.
In the following sections, We will detail all the steps for writing a custom tag.