How is the label_tag's attrs parameter supposed to specified?

68 views
Skip to first unread message

doogster

unread,
Jul 20, 2012, 2:46:45 PM7/20/12
to django...@googlegroups.com
For me, the BoundField.label_tag method's attrs parameter is one of those "what were the designers of Django thinking when they put it in" things. Rather than wondering, I'll ask here.

The way to add HTML attributes to a label is to call label_tag with its attrs parameter set. label_tag is usually called by templates. Templates cannot pass parameters to the methods that they call. Do you see the problem?

When this gets discussed on forums, solutions tend to range from building custom template tags to monkeypatching BoundField.label_tag. (I went with the latter solution here: http://duganchen.ca/rendering-django-forms-for-the-twitter-bootstrap/). None of these solutions are really great, and I am very, very curious as to how it's actually supposed to be done.

Tomas Neme

unread,
Jul 20, 2012, 2:52:47 PM7/20/12
to django...@googlegroups.com
{% for field in form %}
<label for="{{ field.id_for_tag }}" foo="bar">{{ field.label
}}</label>{{ field }}
{% endfor %}

although I think the custom form class is not such a bad solution



--
"The whole of Japan is pure invention. There is no such country, there
are no such people" --Oscar Wilde

|_|0|_|
|_|_|0|
|0|0|0|

(\__/)
(='.'=)This is Bunny. Copy and paste bunny
(")_(") to help him gain world domination.

Doogster

unread,
Jul 27, 2012, 1:37:08 PM7/27/12
to django...@googlegroups.com
A filter that takes a label_tag isn't a bad solution:

@register.filter(is_safe=True)
def label_with_classes(value, arg):

return value.label_tag(attrs={'class': arg})

And then, in the template:

{{ form.my_field|label_with_classes:"class1 class2"}}
> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To post to this group, send email to django...@googlegroups.com.
> To unsubscribe from this group, send email to django-users...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
>
Reply all
Reply to author
Forward
0 new messages