Custom django template filter: Sanitize emails

Still working on my Honyaku mailing list archive site, I needed a template filter to sanitize emails. The filter itself was very simple: it was finding out how to write a template filter that took most of my research.

The filter code

Here's the code for the filter. As I said, pretty simple stuff.

#coding: UTF8
A template filter to sanitize emails.

from django import template
register = template.Library()
import re

def sanitize_emails(text):
    Sanitize emails in the text.
    Blah blah blah blah blah
        => Blah blah blah blah blah
    text = re.sub(r"(\w\w@\w\w)(\w*?\.)",
                  re.I | re.M )

    # Catch cases like ""
    return re.sub(r"(\w@\w\w)(\w*?\.)",
                  re.I | re.M )

Note that despite being known to rail against regular expressions at times, I do believe that they have their uses :).

Where to put the filter

This was the tricky part for me. I eventually found that you put your custom filters in a directory named templatetags, in your application directory. So if your project is myproject, and your app is myapp, the directory structure would look like this:


Then, in your template, you simply load the filter and use it like so:

    {% load sanitize %}

And there you have it. Nice, sanitized emails in your django templates.

Leave a Reply




You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>