Login

Autoescape Migration Helper

Author:
blinkylights
Posted:
January 10, 2008
Language:
Python
Version:
.96
Tags:
autoescape
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. Advanced Search in django admin by visik7 4 years, 6 months ago
  2. plaintext filter by onelson 5 years, 3 months ago
  3. Protect anti robots template tag by marinho 7 years, 2 months ago
  4. Safe template decorator by eternicode 3 years, 2 months ago
  5. Truncate HTML without breaking tags by olau 6 years, 2 months ago

Comments

Please login first before commenting.