Parse a string for BBCode and generate it to (X)HTML by using the postmarkup libary.
In your template for generating (X)HTML:
{% load bbcode %}
{{ value|bbcode }}
In your template for removing BBCode fragments:
{% load bbcode %}
{{ value|strip_bbcode }}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | from django import template
from django.conf import settings
from django.utils.encoding import smart_str, force_unicode
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def bbcode(value):
"""
Generates (X)HTML from string with BBCode "markup".
By using the postmark lib from:
@see: http://code.google.com/p/postmarkup/
"""
try:
from postmarkup import render_bbcode
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError, "Error in {% bbcode %} filter: The Python postmarkup library isn't installed."
return force_unicode(value)
else:
return mark_safe(render_bbcode(value))
bbcode.is_save = True
@register.filter
def strip_bbcode(value):
"""
Strips BBCode tags from a string
By using the postmark lib from:
@see: http://code.google.com/p/postmarkup/
"""
try:
from postmarkup import strip_bbcode
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError, "Error in {% bbcode %} filter: The Python postmarkup library isn't installed."
return force_unicode(value)
else:
return mark_safe(strip_bbcode(value))
bbcode.is_save = True
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Thanks this helped my implement BBCode on my site and I learnt a thing or two about custom template filters while I did it :-)
#
Please login first before commenting.