Switch
Thymeleaf source
<sl:label><sl:switch th:field="*{airplaneMode}"/>Airplane mode</sl:label>Rendered HTML
<label class="label"> <input type="checkbox" role="switch" class="switch" name="airplaneMode"> Airplane mode</label>A switch is a checkbox with role="switch", so a screen reader announces it as on or off and a form submits it as a
checkbox. th:field on a boolean field works as it does on the checkbox, including the numbered id:
put the switch inside its label.
Use a switch for a setting that takes effect as it is, and a checkbox for a choice the user confirms by submitting a form.
Thymeleaf source
<sl:label><sl:switch size="sm" name="compact" checked/>Small</sl:label><sl:label><sl:switch name="regular" checked/>Default</sl:label>Rendered HTML
<label class="label"> <input type="checkbox" role="switch" class="switch" data-size="sm" name="compact" checked> Small</label><label class="label"> <input type="checkbox" role="switch" class="switch" name="regular" checked> Default</label>Invalid
Section titled “Invalid”Thymeleaf source
<sl:label><sl:switch th:field="*{marketing}"/>Marketing emails</sl:label>Rendered HTML
<label class="label"> <input type="checkbox" role="switch" class="switch" name="marketing" aria-invalid="true"> Marketing emails</label>Disabled
Section titled “Disabled”Track and thumb fade together, and so does the label. A disabled switch is not submitted, so Spring leaves out the
hidden marker input it adds for a th:field checkbox: the bound value stays as it was.
Thymeleaf source
<sl:label><sl:switch name="sso" checked disabled/>Single sign-on (managed by your organisation)</sl:label><sl:label><sl:switch name="betaFeatures" disabled/>Beta features (not in your plan)</sl:label>Rendered HTML
<label class="label"> <input type="checkbox" role="switch" class="switch" name="sso" checked disabled> Single sign-on (managed by your organisation)</label><label class="label"> <input type="checkbox" role="switch" class="switch" name="betaFeatures" disabled> Beta features (not in your plan)</label>Attributes
Section titled “Attributes”| Attribute | Values | Default | Description |
|---|---|---|---|
size | sm default | default | Size of the switch. |
Every prop can also be set from an expression: th:size="${...}". Any other attribute passes through to the rendered element, and class is appended.