from django import template
import re
from django.utils.safestring import mark_safe

register = template.Library()

class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])')

@register.filter
def add_class(value, css_class):
    string = unicode(value)
    match = class_re.search(string)
    if match:
        m = re.search(r'^%s$|^%s\s|\s%s\s|\s%s$' % (css_class, css_class, 
                                                    css_class, css_class), 
                                                    match.group(1))
        print match.group(1)
        if not m:
            return mark_safe(class_re.sub(css_class + " " + match.group(1) , 
                                          string))
    else:
        return mark_safe(string.replace('>', ' class="%s">' % css_class))
    return value