Form Field Label HTML Objects

Form fields are a Form Field HTML Object and the label for form fields is also a HTML Object.

The purpose of the HTML Object is to allow you to add or change the attributes for the field label tag before outputting the label tag. Instead of having to manually build out the label tag just to set a custom class value you can set the attribute value and then simply output the label tag. This helps with readability and is often easier to write.

Instead of doing this:

<label for="{{ }}" class="CustomClass">{{ field.label }}</label>

now you can set the class value and then simply output the code:

{% set field.label.class = 'CustomClass' %}
{{ field.label.tag }

You can also manipulate the label text. It's common to add an asterisk to the label if it's required. Below is an example of how that could be done.

{% if field.isRequired %}
    {% set field.label.text = field.label.text ~ ' <em>*</em>' %}
{% endif %}
{{ field.label.tag }}

If the field's label text is "First Name" and the field is required then the above code would output <label for="first-name">First Name <em>*</em></label>.

Display the label tag

You can display the full label tag using the following code:

{{ field.label.tag }}

Note that the above code is assuming that you were looping through the available form fields like so:

{% for field in form.fields %}
    {{ field.label.tag }}
    {{ field.tag }}
{% endfor %}

Available label tag attributes

The following form field label tag attributes are available for you to set or change values:

{{ field.label.class }}
{{ field.label.for }}

You can also set any valid HTML attribute on the label tag such as 'data' attributes.

See HTML Objects for more information about setting attribute values.

Field label text

You can change the field label text before you output it. Below are a few examples.

Set new text:
{% set field.label.text = 'New label text' %}

Append some text
{% set field.label.text = field.label.text ~ ' More Text' %}

Prepend some text
{% set field.label.text = 'Beginning text ' ~ field.label.text %}

While you can also use {% set field.label = 'Label Text' %} to set or change the label text, it's not consistent with how HTML Objects are typically used so we don't recommend it. 


Output the label text

There are two ways to output the label text.

1) {{ field.label.text }} is the recommended way to display just the field text.

2) To avoid breaking older templates {{ field.label }} will also return just the label text.