How to compile template nodes and register tags in Django

Source: Internet
Author: User
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:

  1. Template Tag Name (string ).
  2. 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.