This article mainly introduces compiling functions in the Python Django framework. if you need to use the template tag in the template, you can refer to the template tag, the template parser calls a python function based on the tag content and the template parser itself as a parameter. This function returns an instance of the Node corresponding to the label content of the current template.
For example, write a template tag {% current_time %} that shows the current date }. The label displays the current time based on the strftime format specified by the parameter (see: http://www.djangoproject.com/r/python/strftime. First, it is a good idea to determine the syntax of tags. In this example, labels should be used as follows:
The time is {% current_time "%Y-%m-%d %I:%M %p" %}.
Note:
Yes, this template tag is redundant. Django's default {% now %} completes the same job with a simpler syntax. The template tag is used as an example here.
The analyzer of this function obtains the parameters and creates a Node object:
from django import templateregister = template.Library()def do_current_time(parser, token): try: # split_contents() knows not to split quoted strings. tag_name, format_string = token.split_contents() except ValueError: msg = '%r tag requires a single argument' % token.split_contents()[0] raise template.TemplateSyntaxError(msg) return CurrentTimeNode(format_string[1:-1])
There are many things to note:
Each tag compilation function has two parameters: parser and token. Parser is the template parser object. We do not use it in this example. Token is the statement being parsed.
Token. contents is a string containing the original tag content. In our example, it is 'current _ time "% Y-% m-% d % I: % M % p "'.
The token. split_contents () method splits strings by space and ensures that the strings in quotation marks are not split. Avoid using token. contents. split () (only using standard Python strings for splitting ). It is not robust enough because it simply splits according to all spaces, including spaces in the strings caused by quotation marks.
This function can throw django. template. TemplateSyntaxError, which provides useful information about all syntax errors.
Do not hard encode the tag name in your error message, because the tag name is coupled with your function. Token. split_contents () [0] always records the tag name, even if the tag does not have any parameters.
This function returns a CurrentTimeNode (we will create it later), which contains all the information about the label that the node needs to know. In this example, it only passes the parameter "% Y-% m-% d % I: % M % p ". Use format_string [1:-1] to remove the quotation marks at the beginning and end of the template tag.
The template tag compilation function must return a Node subclass, and other returned values are all incorrect.