Login

BBCode templatefilter (generate & strip)

Author:
b23
Posted:
July 4, 2008
Language:
Python
Version:
.96
Tags:
template templatetag templatefilter bbcode xhmtl
Score:
2 (after 2 ratings)

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

  1. Filter to generate QR codes by javinievas 4 years, 7 months ago
  2. Dom ID by bmihelac 5 years, 3 months ago
  3. Clean-ish memcached key generation by iiie 2 years, 5 months ago
  4. Protect anti robots template tag by marinho 6 years, 9 months ago
  5. Checkbox or radio iterator as template filter by Lacour 4 years, 6 months ago

Comments

xocekim (on July 15, 2009):

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.