- Author:
- limodou
- Posted:
- February 25, 2007
- Language:
- Python
- Version:
- Pre .96
- Score:
- 7 (after 7 ratings)
You can use this tag to "catch" some template snippets and save it into a context variable, then use this variable later.
How to use it
{% catch as var1 %}any tags and html content{% endcatch %}
...
{{ var1 }}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | from django import template
class CatchNode(template.Node):
def __init__(self, nodelist, var_name):
self.nodelist = nodelist
self.var_name = var_name
def render(self, context):
output = self.nodelist.render(context)
context[self.var_name] = output
return ''
def do_catch(parser, token):
"""
Catch the content and save it to var_name
Example::
{% catch as var_name %} ... {% endcatch %}
"""
try:
tag_name, arg = token.contents.split(None, 1)
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents[0]
m = re.search(r'as (\w+)', arg)
if not m:
raise template.TemplateSyntaxError, '%r tag should define as "%r as var_name"' % (tag_name, tag_name)
var_name = m.groups()[0]
nodelist = parser.parse(('endcatch',))
parser.delete_first_token()
return CatchNode(nodelist, var_name)
do_catch = register.tag('catch', do_catch)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.