Created
August 6, 2014 22:24
-
-
Save TimFletcher/034e799c19eb763fa859 to your computer and use it in GitHub Desktop.
Django template filter to add attributes to form fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# From http://vanderwijk.info/blog/adding-css-classes-formfields-in-django-templates/#comment-1193609278 | |
from django import template | |
register = template.Library() | |
@register.filter(name='add_attributes') | |
def add_attributes(field, css): | |
attrs = {} | |
definition = css.split(',') | |
for d in definition: | |
if ':' not in d: | |
attrs['class'] = d | |
else: | |
t, v = d.split(':') | |
attrs[t] = v | |
return field.as_widget(attrs=attrs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is also a problem if you want to add multiple classes (like form-control selectpicker) (https://silviomoreto.github.io/bootstrap-select/examples/#styling).
What I've done is use
collections.defaultdict(str)
instead of a simpledict
, then just add to the css attribute.