elem-go
elem-go copied to clipboard
Add `ClassNames` utility function for conditional CSS class handling
Problem
When conditionally applying CSS classes, developers currently need to manually concatenate strings and manage spacing, which is error-prone:
// Easy to mess up spacing
attrs.Props{
attrs.Class: "btn" +
elem.If(isPrimary, " btn-primary", "") +
elem.If(isDisabled, " btn-disabled", ""),
}
// Forget a space? Broken CSS
attrs.Props{
attrs.Class: "btn" + elem.If(isPrimary, "btn-primary", ""), // Missing space!
}
Proposed Solution
Add a ClassNames utility function to the attrs package that:
- Joins multiple class name strings with spaces
- Automatically filters out empty strings
- Trims whitespace from class names
- Uses
strings.Builderfor optimal performance
Usage Example
isPrimary := true
isDisabled := false
button := elem.Button(
attrs.Props{
attrs.Class: attrs.ClassNames(
"btn",
elem.If(isPrimary, "btn-primary", ""),
elem.If(isDisabled, "btn-disabled", ""),
),
},
elem.Text("Submit"),
)
// Renders: <button class="btn btn-primary">Submit</button>
Implementation Notes
- Should be added to
attrs/utils.go - Needs comprehensive tests covering edge cases (empty strings, whitespace, etc.)
- Should be documented in
attrs/README.md