Login

Create variables within templates

Author:
nkwenti
Posted:
June 27, 2008
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.