Login

Customizable newforms labels with a template tag

Author:
exogen
Posted:
April 9, 2008
Language:
Python
Version:
.96
Tags:
templatetag newforms label
Score:
0 (after 0 ratings)

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

  1. Template Filter attr by marinho 7 years, 3 months ago
  2. Form rendering using a template instead of builtin HTML by leoh 8 years, 1 month ago
  3. FieldsetForm by Ciantic 8 years, 3 months ago
  4. RangeField and RangeWidget by marinho 6 years, 10 months ago
  5. Type checking templatetag filters by marcorogers 5 years, 5 months ago

Comments

Please login first before commenting.