Login

Autoescape Migration Helper

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

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.