- 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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.