- Author:
 - evan_schulz
 - Posted:
 - July 15, 2008
 - Language:
 - Python
 - Version:
 - .96
 - 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
- Add Toggle Switch Widget to Django Forms by OgliariNatan 1 month, 4 weeks ago
 - get_object_or_none by azwdevops 5 months, 2 weeks ago
 - Mask sensitive data from logger by agusmakmun 7 months, 2 weeks ago
 - Template tag - list punctuation for a list of items by shapiromatron 1 year, 9 months ago
 - JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 9 months ago
 
Comments
Please login first before commenting.