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:
- The name of the template tag (string).
- 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.