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

@register.filter
def sanitize_emails(text):
    """
    Sanitize emails in the text.
    Blah blah blah ryan@spam.me.com blah blah
        => Blah blah blah ry..@..am.me.com blah blah
    "
""
    text = re.sub(r"(\w\w@\w\w)(\w*?\.)",
                  r"..@..\2",
                  text,
                  re.I | re.M )

    # Catch cases like "I.b@foolish.com"
    return re.sub(r"(\w@\w\w)(\w*?\.)",
                  r".@..\2",
                  text,
                  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:

myproject/
    __init__.py
    manage.py
    myapp/
        __init__.py
        models.py
        templates/
            …
        templatetags/
            __init__.py
            sanitize.py
        …
    …

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

    {% load sanitize %}
    <p>{{post.text|escape|sanitize_emails}}</p>

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>