Skip to content

Instantly share code, notes, and snippets.

@dryan
Created November 18, 2009 00:43
Show Gist options
  • Select an option

  • Save dryan/237435 to your computer and use it in GitHub Desktop.

Select an option

Save dryan/237435 to your computer and use it in GitHub Desktop.
Django middleware for wrapping ampersands in a span
# Requires BeautifulSoup
class Ampersands(object):
from BeautifulSoup import BeautifulSoup
import re
def process_response( self, request, response ):
if response.has_header('Content-Type') and response['Content-Type'].startswith('text/html') and request.META['PATH_INFO'][0:7] != '/admin/':
content = BeautifulSoup(response.content)
try:
for t in content.body.findAll(text = re.compile( r'.*&.*' )):
text = unicode(t)
if not str(t.parent) == '<span class="amp">&amp;</span>':
text = text.replace('&amp;', '<span class="amp">&amp;</span>')
t.replaceWith(text)
response.content = content
except:
pass
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment