Always Use the Best Ampersand Available

17 November 2009

In the spirit of Dan Cederholm, who reminds us that in the spirit of The Elements of Typographic Style, we should always use the best ampersand available. To that end I’ve whipped up a short Django middleware that wraps any ampersands it finds in <span class="amp">&amp;</span>. For suggestions on how to style this class, check out Dan’s article Use the Best Ampersand Available.

# 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)
        for t in content.body.findAll(text = re.compile( r'.*&.*' )):
          text = unicode(t)
          if not str(t.parent) == '&':
            text = text.replace('&', '&')
        response.content = content
    return response