Note: There is a built in template tag called urlize that does the same thing.

The following filter will parse out links from the text passed to it and generate anchor tags for them. It will also insert spaces into the textual part of the link, so that long links break properly. Also, you may pass an argument to the filter, specifying the class attribute of the link.

from django import template
import re

register = template.Library()
regex = re.compile(r'(([a-zA-Z]+)://[^ \t\n\r]+)', re.MULTILINE)

def linkify(value, arg=''):
    def _spacify(s, chars=40):
        if len(s) <= chars:
            return s
        for k in range(len(s) / chars):
            pos = (k + 1) * chars
            s = s[0:pos] + ' ' + s[pos:]
        return s
    def _replace(match):
        href =
        cls = arg and (' class="%s"' % arg) or ''
        return '<a href="%s"%s>%s</a>' % (href, cls, _spacify(href))
    return regex.sub(_replace, value)

register.filter('linkify', linkify)


{{ variable|linkify:"my_link_class" }}
Last modified 14 years ago Last modified on 04/12/09 17:59:10
Back to Top