This article mainly introduces how to compile template nodes and register tags in Django. Django is the most famous among the various popular Python frameworks. For more information, see
Compile template nodes
The second step of writing custom labels is to define a Node subclass with the render () method. To continue with the previous example, we need to define CurrentTimeNode:
import datetimeclass CurrentTimeNode(template.Node): def __init__(self, format_string): self.format_string = str(format_string) def render(self, context): now = datetime.datetime.now() return now.strftime(self.format_string)
These two functions (_ init _ () and render () correspond directly to the two steps (Compilation and rendering) in template processing. In this way, the initialization function only needs to store the format strings to be used later, and the render () function does the real work.
Like the template filter, these rendering functions should quietly capture errors rather than throw errors. Template labels can only throw errors during compilation.
Register tags
Finally, you need to register this tag with the Library instance of your module. Registering a custom tag is similar to registering a custom filter (as described above ). You only need to instantiate a template. Library instance and then call its tag () method. For example:
Register. tag ('current _ time', do_current_time)
The tag () method requires two parameters:
- Template Tag Name (string ).
- Compile the function.
Similar to the registration filter, you can also use the register. tag modifier in Python2.4 and later versions:
@register.tag(name="current_time")def do_current_time(parser, token): # ...@register.tagdef shout(parser, token): # ...
If you ignore the name parameter as in the second example, Django uses the function name as the tag name.