Django: Creating custom tag and endtag type template tags

A single tag is normally sufficient when it comes to template based operations.

However, sometimes you'll need to capture the contents of the template before choosing what to do with it.

For example, the built-in template tag "if" and "endif".

The tag captures anything between the if/endif tags and then does something with it.

The example below is straight from Django docs.

{% upper %}{{ name }} will appear in uppercase.{% endupper %}

The usage of the template tag seems simple enough. Uppercase all the text between the tags.

The creation of the custom tag is below.

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 magic line there is self.nodelist.render(context), which pulls out all the content in between and renders it properly before performing the upper-casing operation.

[ Source ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog