BBCode Python Module
In the last few weeks I have been tinkering with a dynamic website created with Turbogears, but that's not what this blog entry is about. The website I have in mind is similar to a forum in that most of the content come from the users (can't tell you exactly what it is just yet). I wanted a way for users to post comments with simple formatting, but I didn't want to let them enter straight html - for all the problems that would cause. No doubt, some wise-guy would figure out that he could enter the tag! So I decided to implement something like BBCode, which I dubbed 'Post Markup'.
But once I came close to finishing Post Markup, I realised it was so much like BBCode, it was BBCode (which doesn't seem to have any strict definition anyway). My BBCode parser is deliberately quite relaxed, it will try to make sense of the BBCode rather than throwing errors. It will close open tags as well as handle overlapping tags so that it always produces valid XHTML snippets.
You can download postmarkup.py here. This code is 'politeware', you may use it for any purpose you want as long as you say 'thank you' and you promise not to sue me if it breaks! Let me know if you have any suggestions or bug-fixes.
Here's a quick example of basic use.
import postmarkup markup = postmarkup.PostMarkup().default_tags() bbcode = "[b]Hello, World![/b]" print markup.render_to_html(bbcode)
There are comments in the module. If you have any questions, please email or (better) post a comment here so I can build up documentation.
The following is a cut and paste of the test output. It shows the basic tags (bold, italic etc) and more advanced tags.
[b]Hello[/b]
[s]Strike through[/s]
[b]bold [i]bold and italic[/b] italic[/i]
[google]Will McGugan[/google]
[wiki Will McGugan]Look up my name in Wikipedia[/wiki]
[link http://www.willmcgugan.com]My homepage[/link]
[link]http://www.willmcgugan.com[/link]
[quote Will said...]BBCode is very cool[/quote]
Will said...BBCode is very cool
[b]Long test[/b] New lines characters are converted to breaks. Tags my be [b]ove[i]rl[/b]apped[/i]. [i]Open tags will be closed.
New lines characters are converted to breaks. Tags my be overlapped.
Open tags will be closed.