Label
Renders an accessible label associated with controls.
TailwindCSS
Alpine.js
package showcase
import "github.com/axzilla/templui/pkg/components"
templ CheckboxWithLabel() {
<div class="flex items-center gap-2">
@components.Checkbox(components.CheckboxProps{
ID: "checkbox-with-label",
})
@components.Label(components.LabelProps{
For: "checkbox-with-label",
Text: "Accept terms and conditions",
})
</div>
}
package components
type LabelProps struct {
ID string // Optional label ID
For string // Target input ID
Text string // Label text
Error string // Error message
Class string // Additional CSS classes
DisabledClass string // Additional CSS classes when the input is disabled
}
templ LabelScript() {
{{ handle := templ.NewOnceHandle() }}
@handle.Once() {
<script defer nonce={ templ.GetNonce(ctx) }>
document.addEventListener('alpine:init', () => {
Alpine.data('label', () => ({
getClass() {
if (this.$refs[this.$el.getAttribute('for')]?.disabled ) {
return this.$el.dataset.disabledStyle
}
}
}));
});
</script>
}
}
// Label renders a form label with error and disabled states
templ Label(props LabelProps) {
<label
x-data="label"
id={ props.ID }
for={ props.For }
class={
// Styling
"text-sm font-medium leading-none",
// Utility
templ.KV("text-destructive", len(props.Error) > 0),
// Custom
props.Class,
}
if props.DisabledClass != "" {
data-disabled-style={ props.DisabledClass }
} else {
data-disabled-style="opacity-50 cursor-not-allowed"
}
x-bind:class="getClass"
>
{ props.Text }
</label>
}