= CookBook - Template filter BBCode = django version : 0.96 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 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 ---- If the code is a block, how to parse it? -- Limodou {{{{% filter bbcode %}data to translate{% endfilter %}}}} -- nesh What I siad is: {{{ [code] def p(a): print a [/code] }}} The "[code]" is a paragraph, but not a single string line. How to parse it? And if the bbcode has newline, there seems no process for it. ---- Limodou ---- I noticed that there is no handling of quote where a user name is given. phpBB, for example, has {{{[quote="A User's Name"]text[/quote]}}}. ---- Powerlord