BBCode markup in Django

Why BBCode?

I'm a fan of reStructuredText but faced the problem of being forced to use two versions of one text field: one without any markup for RSS, one with markup for rendering HTML. I found no easy solution how to remove reST markup, so I decided to change markup for this project.

I chose BBCode because it's pretty easy to understand for ordinary users and it's easy to remove since BBCode uses a syntax similar to HTML, just with squared brackets.

Example tags: [b][i][u][s][color][size][link][img][list][code][center][quote]

Will McGugan wrote postmarkup (under the New BSD license), a cool module which generates XTHML from BBCode and also removes BBCode markup, exactly what I needed - thanks!

postmarkup can be downloaded from http://code.google.com/p/postmarkup/

I installed postmarkup with setup.py.

$ sudo python setup.py install

Next I created in my application folder "blog" a folder called "templatetags", put in it an empty __init.py__ and created a file called "bbcode.py".

|-- blog
| |-- models.py
| |-- templatetags
| | |-- __init__.py
| | `-- bbcode.py
`-- views.py

bbcode.py

The bbcode function generates a BBcode formatted string in (X)HTML. It uses the "render_bbcode" function from the "postmarkup" module. The "strip_bbcode" strips any BBCode markup. For easier reading, please see the version on http://www.djangosnippets.org/snippets/853/.

Use it in your templates, load the bbcode templatetags first and append it to your variable:

{% load bbcode %}
HTML: {{ value|bbcode }}
remove any BBCode: {{ value|strip_bbcode }}

postmarkup also makes it possible to highlight syntax code by using Pygments.

URLs