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. Convert XHTML-compatible shorttag to HTML-compatible tag. by clamothe 5 years, 1 month ago
  2. Multiple-Submit-Button Widget for Choice Field by Archatas 4 years, 9 months ago
  3. Custom CSS class in Form with template tag filter by kegan 3 years, 11 months ago
  4. Custom CSS class in Form with template tag filter by fernandogrd 1 year, 7 months ago
  5. custom css classes for newforms by robharvey 6 years ago

Comments

kmike (on March 19, 2011):

Another implementation that doesn't use regexes and wraps field.as_widget method with updated widget attributes instead:

http://pypi.python.org/pypi/django-widget-tweaks

#

(Forgotten your password?)