First, the registration method is generally to instantiate a template. Library first. For example:
from django import templateregister = template.Library()
1. register the custom filter method
Register. filter ('A', B)
The two parameters in the filter () method are the name of A filter (A string) and the filter function B.
2. Registration of Custom template labels
Register. tag ('A', B)
The tag () method requires two parameters: Template tag name A and compiled function B.
3. Methods for registering simple tags, such as if, for, ifequal, etc.
Register. simple_tag ()
The function passed by this auxiliary function only has (single) parameters. The quotation marks (if any) on both sides of the parameter have been truncated, so it is possible to receive only one normal Unicode string.
4. Register a method containing tags
Register.inclusion_tag('A.html ') (B)
The inclusion_tag () method requires two parameters: File A of the template and compiled function B.
Sometimes, the context containing the tag needs to access the context of the parent template. in this case, you can use the takes_context option, that is, set takes_context = True, and the tag does not require a parameter. The following Python function will include a parameter: The template context when the tag is called.
@ Register.inclusion_tag('a.html ', takes_context = True) def jump_link (context): # The parameter must be context return {'link': context ['home _ link'], 'title ': context ['home _ title'], # Here there are variables pointing to the home page, that is, the values of the variables link and title in home_link and home_title}
After creating a.html, it may contain the following content:
The link and title of XXXXX {title} xxxxxx are obtained from the content in home_link and home_title respectively.
If you want to call this parameter, you can directly load its library and call it {jump_link} without parameters }}
5. Compile a custom template Loader
Load_template_source (template_name, template_dirs = None)
Template_name is the name of the template to be loaded, similar to loader. get_template () or loader. select_template ()
Template_dirs is an optional search directory list that replaces TEMPLATE_DIRS.
If the loader can successfully load a template, A tuples (template_source, template_path), template_source: Template string compiled by the template engine, and template_path: Template path to be loaded will be returned. If the loader fails to load the template, the django. template. TemplateDoesNotExist exception is triggered.
Note: @ xxxx is displayed in the code above. The syntax is set up in python 2.4 and later versions. That is:
@ Register. tag (name = "A") # name of a filter (A string) def B (parser. token ):#.....
Or you can directly write it as follows:
@register.tagdef B(parser,token): #......
Django uses function name B as the tag name.
Here is only one example. Other statements are similar. If you have different opinions, you are welcome to discuss them.