Create variables within templates

 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
33
from django import template
from django.utils import simplejson
import re

register = template.Library()

class VariablesNode(template.Node):
    def __init__(self, nodelist, var_name):
        self.nodelist = nodelist
        self.var_name = var_name
        
    def render(self, context):
        source = self.nodelist.render(context)
        context[self.var_name] = simplejson.loads(source)
        return ''

@register.tag(name='var')
def do_variables(parser, token):
    try:
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        msg = '"%s" tag requires arguments' % token.contents.split()[0]
        raise template.TemplateSyntaxError(msg)
    m = re.search(r'as (\w+)', arg)
    if m:
        var_name, = m.groups()
    else:
        msg = '"%s" tag had invalid arguments' % tag_name
        raise template.TemplateSyntaxError(msg)
           
    nodelist = parser.parse(('endvar',))
    parser.delete_first_token()
    return VariablesNode(nodelist, var_name)

More like this

  1. CallTag - Just like include, but can pass parameters to it by limodou 7 years, 1 month ago
  2. "Zoom in" on rendered HTML that the test client returns by peterbe 4 years, 12 months ago
  3. Variable inspect filter by buriy 5 years, 11 months ago
  4. Plaintext format (advanced spaceless) by hoverhell 3 years ago
  5. Capture template output as a variable by kcarnold 6 years, 3 months ago

Comments

(Forgotten your password?)