Another Mike

  • Home
  • Archive

Custom Django tags

12/17/2010

I doubt if this method prevents much spam, but I wanted to learn how to implement a custom Django tag. The documentation for tags seems fairly straight-forward, but it often splits up examples into small code pieces which can make it seem more difficult. (Or maybe it's just that there's too many places to look for a quick answer.)

Here's the PHP method rewritten as a Django tag. Please let me know in the comments if there's a better way, I'm just getting reacquainted with the language.

from random import randrange
from django import template
register = template.Library()
from django.template.defaultfilters import stringfilter

def html_escape(c):
    if randrange(0, 2):
        return '&#' + str(ord(c)) + ';'
    else:
        return '&#X' + hex(ord(c))[2:] + ';'

@register.filter(name='encode_email')

@stringfilter
def encode_email(email):
    return ''.join(map(html_escape, email))

Of course, tags must live in a Django app. Just run python manage.py startapp myapp and add it to the INSTALLED_APPS in settings.py.

Then, create the folder myapp/templatetags/ and the script myapp/templatetags/init.py. Place the script in the templatetags folder.

Next, load the tag in your template using {% load my_tag %}. Lastly, use the tag like: "mailto:myemail"|encode_email.

Of course, Django will automatically escape the output. So to temporarily disable escaping, use this:

  {{ "mailto:myemail"|encode_email }}