This template tag and suggested template allow greater control over rendering <label>
tags for your newforms fields than using field.label_tag
. I save the provided Python code in my app as templatetags/forms.py
(although this name may conflict in the future).
The simplest usage:
{% label field %}
One use case is adding class="required"
to the label tag for required fields instead of inserting markup elsewhere--this is done in the given example template.
Alternate label text and tag attributes can be passed to the inclusion tag:
{% label field "Alt. label" 'class=one,id=mylabel' %}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | from django.template import Library
from django.newforms.util import flatatt
register = Library()
@register.inclusion_tag("forms/label.html")
def label(field, contents=None, attrs=None):
if isinstance(attrs, basestring):
attrs = [tuple(pair.split('=')) for pair in attrs.split(',')]
attrs = dict(attrs or {})
widget = field.field.widget
for_id = widget.id_for_label(widget.attrs.get('id') or field.auto_id)
contents = contents or field.label
return {'field': field, 'id': for_id, 'contents': contents, 'attrs': attrs}
@register.filter
def attrlist(attrs):
attrs = dict(attrs)
return flatatt(attrs)
attrlist.is_safe = True
# My "forms/label.html" looks like this...
"""
{% load forms %}
{% if not field.is_hidden %}
{% with field.field.required as required %}
<label for="{{ id }}"{{ attrs|attrlist }}{% if required and not attrs.class %} class="required"{% endif %}>
{{ contents }}
</label>
{% endwith %}
{% endif %}
"""
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.