Changes between Initial Version and Version 1 of LinkifyFilter


Ignore:
Timestamp:
Oct 4, 2006, 12:12:14 PM (18 years ago)
Author:
dcwatson@…
Comment:

added LinkifyFilter

Legend:

Unmodified
Added
Removed
Modified
  • LinkifyFilter

    v1 v1  
     1The 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.
     2
     3{{{
     4from django import template
     5import re
     6
     7register = template.Library()
     8regex = re.compile( r'(([a-zA-Z]+)://[^ \t\n\r]+)', re.MULTILINE )
     9
     10def linkify( value, arg = '' ):
     11    def _spacify( s, chars = 40 ):
     12        if len(s) <= chars:
     13            return s
     14        for k in range( len(s) / chars ):
     15            pos = (k + 1) * chars
     16            s = s[0:pos] + ' ' + s[pos:]
     17        return s
     18    def _replace( match ):
     19        href = match.group( 0 )
     20        cls = ' class="%s"' % arg if arg else ''
     21        return '<a href="%s"%s>%s</a>' % (href, cls, _spacify(href))
     22    return regex.sub( _replace, value )
     23
     24register.filter( 'linkify', linkify )
     25}}}
     26
     27Usage:
     28
     29{{{
     30{{ variable|linkify:"my_link_class" }}
     31}}}
Back to Top