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