Attributes are passed directly into the element function or applied via modifiers. Elementary uses generics to ensure attributes are type-safe for the specific tag being used.
Inline Attributes
Attributes are placed immediately after the tag name:
div(.data("hello", value: "there")) { ... }
Conditional Attributes
Use the .attributes(_:when:) modifier to apply attributes based on a boolean condition:
li { text }
.attributes(.class("important"), when: isImportant)
Attribute Fallthrough
If you expose the HTMLTag type in your component's body, attributes applied to the component will 'fall through' to the underlying element:
struct Button: HTML {
var text: String
var body: some HTML<HTMLTag.input> {
input(.type(.button), .value(text))
}
}
// Usage:
Button(text: "Hello").attributes(.autofocus)
Note on Merging: By default, class and style attributes are merged (using spaces or semicolons). All other attributes are overwritten if a duplicate is provided.
// Inline
div(.data("hello", value: "there")) { ... }
// Conditional
li { text }
.attributes(.class("important"), when: isImportant)
// Fallthrough
struct Button: HTML {
var text: String
var body: some HTML<HTMLTag.input> {
input(.type(.button), .value(text))
}
}
Button(text: "Hello").attributes(.autofocus)