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 = match.group(0)
        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)

Usage:

{{ variable|linkify:"my_link_class" }}
Last modified 16 years ago Last modified on Apr 12, 2009, 12:59:10 PM
Note: See TracWiki for help on using the wiki.
Back to Top