| 1 | = CookBook - Template filter BBCode = |
| 2 | django version : 0.91 |
| 3 | |
| 4 | Many boards allow BBCode to format posts without allowing HTML. This is a save way to allow things like urls, emails, lists, etc. |
| 5 | |
| 6 | 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. |
| 7 | |
| 8 | 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. |
| 9 | |
| 10 | '''bbcode.py:''' |
| 11 | {{{ |
| 12 | #!python |
| 13 | |
| 14 | import re |
| 15 | from django.core import template |
| 16 | register = template.Library() |
| 17 | |
| 18 | @register.filter |
| 19 | def bbcode(value): |
| 20 | |
| 21 | bbdata = [ |
| 22 | (r'\[url\](.+?)\[/url\]', r'<a href="\1">\1</a>'), |
| 23 | (r'\[url=(.+?)\](.+?)\[/url\]', r'<a href="\1">\2</a>'), |
| 24 | (r'\[email\](.+?)\[/email\]', r'<a href="mailto:\1">\1</a>'), |
| 25 | (r'\[email=(.+?)\](.+?)\[/email\]', r'<a href="mailto:\1">\2</a>'), |
| 26 | (r'\[img\](.+?)\[/img\]', r'<img src="\1">'), |
| 27 | (r'\[img=(.+?)\](.+?)\[/img\]', r'<img src="\1" alt="\2">'), |
| 28 | (r'\[b\](.+?)\[/b\]', r'<b>\1</b>'), |
| 29 | (r'\[i\](.+?)\[/i\]', r'<i>\1</i>'), |
| 30 | (r'\[u\](.+?)\[/u\]', r'<u>\1</u>'), |
| 31 | (r'\[quote\](.+?)\[/quote\]', r'<div style="margin-left: 1cm">\1</div>'), |
| 32 | (r'\[center\](.+?)\[/center\]', r'<div align="center">\1</div>'), |
| 33 | (r'\[code\](.+?)\[/code\]', r'<tt>\1</tt>'), |
| 34 | (r'\[big\](.+?)\[/big\]', r'<big>\1</big>'), |
| 35 | (r'\[small\](.+?)\[/small\]', r'<big>\1</big>'), |
| 36 | ] |
| 37 | |
| 38 | for bbset in bbdata: |
| 39 | p = re.compile(bbset[0], re.DOTALL) |
| 40 | value = p.sub(bbset[1], value) |
| 41 | |
| 42 | #The following two code parts handle the more complex list statements |
| 43 | temp = '' |
| 44 | p = re.compile(r'\[list\](.+?)\[/list\]', re.DOTALL) |
| 45 | m = p.search(value) |
| 46 | if m: |
| 47 | items = re.split(re.escape('[*]'), m.group(1)) |
| 48 | for i in items[1:]: |
| 49 | temp = temp + '<li>' + i + '</li>' |
| 50 | value = p.sub(r'<ul>'+temp+'</ul>', value) |
| 51 | |
| 52 | temp = '' |
| 53 | p = re.compile(r'\[list=(.)\](.+?)\[/list\]', re.DOTALL) |
| 54 | m = p.search(value) |
| 55 | if m: |
| 56 | items = re.split(re.escape('[*]'), m.group(2)) |
| 57 | for i in items[1:]: |
| 58 | temp = temp + '<li>' + i + '</li>' |
| 59 | value = p.sub(r'<ol type=\1>'+temp+'</ol>', value) |
| 60 | |
| 61 | return value |
| 62 | }}} |