Login

CatchTag - Catching the content and saving it to a variable

Author:
limodou
Posted:
February 25, 2007
Language:
Python
Version:
Pre .96
Tags:
tag
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

  1. Duplicating Template Tag by skarphace 3 years, 11 months ago
  2. Support for {% macro %} tags in templates, version 2 by mludvig 8 years ago
  3. ExprTag - Calculating python expression and saving the result to a variable by limodou 8 years, 6 months ago
  4. Simple template tag to do |stringformat filter with format from a variable by leopd 4 years, 4 months ago
  5. Switch template tag by adurdin 7 years ago

Comments

Please login first before commenting.