= CookBook - Template filter BBCode = django version : 0.91 Many boards allow BBCode to format posts without allowing HTML. This is a save way to allow things like urls, emails, lists, etc. This filter should be used in conjunction with the escape filter so you first escape the variable to strip out html and then filter it through bbcode. Please note that this is a quickly written piece of code, and it isn't even fully tested. It is up to you to test it and improve it :) Feel free to edit it right here to make it even better. '''bbcode.py:''' {{{ #!python import re from django.core import template register = template.Library() @register.filter def bbcode(value): bbdata = [ (r'\[url\](.+?)\[/url\]', r'\1'), (r'\[url=(.+?)\](.+?)\[/url\]', r'\2'), (r'\[email\](.+?)\[/email\]', r'\1'), (r'\[email=(.+?)\](.+?)\[/email\]', r'\2'), (r'\[img\](.+?)\[/img\]', r''), (r'\[img=(.+?)\](.+?)\[/img\]', r'\2'), (r'\[b\](.+?)\[/b\]', r'\1'), (r'\[i\](.+?)\[/i\]', r'\1'), (r'\[u\](.+?)\[/u\]', r'\1'), (r'\[quote\](.+?)\[/quote\]', r'
\1
'), (r'\[center\](.+?)\[/center\]', r'
\1
'), (r'\[code\](.+?)\[/code\]', r'\1'), (r'\[big\](.+?)\[/big\]', r'\1'), (r'\[small\](.+?)\[/small\]', r'\1'), ] for bbset in bbdata: p = re.compile(bbset[0], re.DOTALL) value = p.sub(bbset[1], value) #The following two code parts handle the more complex list statements temp = '' p = re.compile(r'\[list\](.+?)\[/list\]', re.DOTALL) m = p.search(value) if m: items = re.split(re.escape('[*]'), m.group(1)) for i in items[1:]: temp = temp + '
  • ' + i + '
  • ' value = p.sub(r'', value) temp = '' p = re.compile(r'\[list=(.)\](.+?)\[/list\]', re.DOTALL) m = p.search(value) if m: items = re.split(re.escape('[*]'), m.group(2)) for i in items[1:]: temp = temp + '
  • ' + i + '
  • ' value = p.sub(r'
      '+temp+'
    ', value) return value }}} An alternative is an XHTML compliant and very well tested bbcode parser I wrote, now included in Ian Holsman's forum repository: http://svn.zilbo.com/svn/django/common/forum