Django: Creating custom tag and endtag type template tags

0 comments

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 ]

0 comments:

Post a Comment

Leave your thoughts ...
---
If you are having trouble with copy/pasting in comments, you need to sign in or click 'Preview'. For more information about this Firefox bug, see here.

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