Add CSS class template filter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import re
from django.utils.safestring import mark_safe
from django import template
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(match.group(1) + " " + css_class, 
                                          string))
    else:
        return mark_safe(string.replace('>', ' class="%s">' % css_class))
    return value

More like this

  1. Django filter stack to cleanup WYSIWYG output by jbergantine 2 years, 7 months ago
  2. Dynamically add css-classes to formfields by Lacour 2 years, 9 months ago
  3. whitespaceoptimize block tag by peterbe 5 years, 7 months ago
  4. Pygmentify a code using template filter by tamizhgeek 2 years, 11 months ago
  5. Page numbers with ... like in Digg by Ciantic 5 years ago

Comments

(Forgotten your password?)