Login

Create variables within templates

Author:
nkwenti
Posted:
June 27, 2008
Language:
Python
Version:
.96
Tags:
tag json css variables var
Score:
8 (after 8 ratings)

Here is a Django template tag that allows you to create complex variables specified in JSON format within a template.

It enables you to do stuff like:

{% var as person %}
{
     "firstName": "John",
     "lastName": "Smith",
      "address": {
          "streetAddress": "21 2nd Street",
          "city": "New York",
          "state": "NY",
          "postalCode": 10021
      },
      "phoneNumbers": [
          "212 555-1234",
          "646 555-4567"
      ]
  }
 {% endvar %}

 <p>{{person.firstName}}, </br>
    {{person.address.postalCode}}, </br>
    {{person.phoneNumbers.1}}
 </p>

This tag also enables me to do dynamic CSS using as follows:

# urlpatters
urlpatterns = patterns('',
    (r'^css/(?P<path>.*\.css)$', 'get_css'),
)

#views
def get_css(request, path):
    return render_to_response('css/%s' % path, {}, 
        mimetype="text/css; charset=utf-8")

# dynamic css within in /path/to/app/templates/css'
{% load var %}
{% var as col %}
{
    "darkbg": "#999",
    "lightbg": "#666"
}
{% endvar %}

{% var as dim %}
{
    "thinmargin": "2em",
    "thickmargin": "10em"
}
{% endvar %}

body {
    background: {{col.darkbg}}; 
    margin: {{dim.thinmargin}};
}
 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 8 years, 5 months ago
  2. "Zoom in" on rendered HTML that the test client returns by peterbe 6 years, 3 months ago
  3. Variable inspect filter by buriy 7 years, 3 months ago
  4. Plaintext format (advanced spaceless) by hoverhell 4 years, 3 months ago
  5. Capture template output as a variable by kcarnold 7 years, 6 months ago

Comments

Please login first before commenting.