analysis until another template label
Template tags can work like blocks that contain other tags (think {% if%}, {% for%}, and so on). To create a template tag like this, use Parser.parse () in your compilation function.
The standard {% comment%} tag is implemented as follows:
def do_comment (parser, token): nodelist = Parser.parse ((' endcomment ',)) Parser.delete_first_token () Return Commentnode () class Commentnode (template. Node): def render (self, context): return '
Parser.parse () receives a tuple that contains the name of the template tag that needs to be parsed as a parameter. It returns a Django.template.NodeList instance, which is a list of all the node objects that were encountered by the parser before resolving the tags specified in any tuple.
So in the previous example, NodeList is the list of all nodes between {% comment%} and {% endcomment%}, not including {% comment%} and {% endcomment%} itself.
After Parser.parse () is called, the parser has not cleared the {% endcomment%} label, so the code needs to explicitly call Parser.delete_first_token () to prevent the label from being processed two times.
Then Commentnode.render () simply returns an empty string. All content between {% comment%} and {% endcomment%} is ignored.
Analyze to another template label and save content
In the previous example, Do_comment () discarded all content between {% comment%} and {% endcomment%}. Of course, you can also modify and use the following tags between the content.
For example, this custom template tag {% upper%}, which will turn its own and {% Endupper%} contents into uppercase:
{% UPPER%} This would appear in uppercase, {{user_name}}. {% Endupper%}
As in the previous example, we will use Parser.parse (). This time, we pass the resulting nodelist to Node:
def do_upper (parser, token): nodelist = Parser.parse ((' Endupper ',)) Parser.delete_first_token () return Uppernode (NodeList) class Uppernode (template. Node): def __init__ (self, nodelist): self.nodelist = NodeList def render (self, context): output = Self.nodelist.render (context) return Output.upper ()
The only new concept here is the Self.nodelist.render (context) in Uppernode.render (). It simply calls render () for each node in the list of nodes.