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

  1. Type checking templatetag filters by marcorogers 5 years, 1 month ago
  2. a simple tag with context by dsblank 5 years, 3 months ago
  3. Enhancing template tags with "as variable" syntax by ctrochalakis 5 years, 7 months ago
  4. Manipulate URL query strings using context variables using a template tag by JHsaunders 4 years, 5 months ago
  5. "Partial Templates" - an alternative to "include" by vigrid 6 years, 1 month ago

Comments

Please login first before commenting.