Version 1 (modified by dcwatson@…, 18 years ago) ( diff )

added LinkifyFilter

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 = ' class="%s"' % arg if arg else ''
        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" }}
Note: See TracWiki for help on using the wiki.
Back to Top