CatchTag - Catching the content and saving it to a variable

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

Comments

(Forgotten your password?)