Login

Parse TemplateTag Variables Safely

Author:
evan_schulz
Posted:
July 15, 2008
Language:
Python
Version:
.96
Tags:
templatetag
Score:
1 (after 1 ratings)

Often times I want to be able to interchangeably pass either literal strings or context variables to a custom templatetag. This function first checks a string for the existence of surrounding quotes and uses the string inside. If the string didn't explicitly use quotes it checks to see if it can resolve the string as a context variable. As a fallback the function will simply return the full string.

Example: {% get_latest_by_tag 'django' %} {% get_latest_by_tag object.tag %}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django.template import Variable, VariableDoesNotExist

QUOTED_STRING = re.compile(r'^["\'](?P<noquotes>.+)["\']$')

def handle_var(self, value, context):
  stringval = QUOTED_STRING.search(value)
  if stringval:
    return stringval.group('noquotes')
  else:
    try:    
      return Variable(value).resolve(context)
    except VariableDoesNotExist:
      return value

More like this

Comments

Please login first before commenting.