How to write template nodes and register tags in Django

Source: Internet
Author: User
Writing template Nodes

The second step in writing a custom label is to define a Node subclass that has a 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 in the template processing (compilation and rendering). In this way, the initialization function only needs to store the format string to be used later, and the render () function does the real work.

As with template filters, these render functions should silently catch errors, rather than throw errors. Template tags only allow errors to be thrown at compile time.
Register label

Finally, you need to register this tag with your module's library instance. Registering a custom label is very similar to registering a custom filter (as described earlier). Just instantiate a template. The Library instance then calls its tag () method. For example:

Register.tag (' Current_time ', do_current_time)

The tag () method requires two parameters:

    1. The name of the template tag (string).
    2. The compilation function.

Similar to registering filters, you can also use the Register.tag adorner in Python2.4 and above:

@register. Tag (name= "Current_time") def do_current_time (parser, token): # ... @register. Tagdef Shout (parser, token): # ...

If you omit the name parameter as in the second example, Django uses the function name as the label name.

  • Related Article

    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.