I'm outputting fields of a form in a template like this {{ form.first_name }}
and I'd like to add a class (eg. blueprint's span-x-class) to it. So I'd like to know if there's a nice readymade solution (template filter) for that, which I could use in the fashion {{ form.first_name|add_class:"span-4" }}
? (I just want to know if Django's developers or anybody has thought of that yet without my knowledge before doing it on my own)
To solve this I made my own template filter, you can apply it on any tag, not just input elements!
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
You only need to install Django widget_tweaks
pip install django-widget-tweaks
After you can to do something like that on your template:
{{ form.search_query|attr:"type:search" }}
--
Read all about it here.