- Author:
- blinkylights
- Posted:
- January 10, 2008
- Language:
- Python
- Version:
- .96
- Score:
- 0 (after 0 ratings)
In the process of adapting to the new autoescaping thing, I've occasionally run into the sad situation where my development Django instance needs autoescape template tags in order to work, but when that code goes into production, I'm on a pre-autoescape Django revision. Hilarious hijinx ensue.
This snippet will attempt to load the new safe and force_safe filters and the autoescape template tag - failing the imports, it'll safely do nothing. The effect is that if you write templates for post-autoescape, but you still need them to work in pre-autoescape, this'll prevent the new filters and tags from causing errors in your older Django instances.
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 34 35 36 37 38 39 | from django import template
register = template.Library()
@register.filter(name="safe")
def safesafe(value):
try:
from django.template.defaultfilters import safe
return safe(value)
except ImportError:
return value
@register.filter(name="force_escape")
def safeforce_escape(value):
try:
from django.template.defaultfilters import force_escape
return force_escape(value)
except ImportError:
return value
class IgnoreAutoEscapeNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
output = self.nodelist.render(context)
return output
@register.tag("autoescape")
def safeautoescape(parser, token):
try:
from django.template.defaulttags import autoescape
return autoescape(parser, token)
except ImportError:
nodelist = parser.parse(('endautoescape',))
parser.delete_first_token()
return IgnoreAutoEscapeNode(nodelist)
|
More like this
- Add Toggle Switch Widget to Django Forms by OgliariNatan 3 days ago
- get_object_or_none by azwdevops 3 months, 3 weeks ago
- Mask sensitive data from logger by agusmakmun 5 months, 3 weeks ago
- Template tag - list punctuation for a list of items by shapiromatron 1 year, 7 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 8 months ago
Comments
Please login first before commenting.