Custom modifiers allow you to create reusable styling and behavior modifications for your HTML elements.
To create a custom modifier, follow these steps:
HTMLModifier
body(content: some HTML) -> any HTML
methodHTML
to make your modifier easily accessibleHere's a simple example that makes text blue:
struct BlueTextModifier: HTMLModifier {
func body(content: some HTML) -> any HTML {
content.style("color: #0066cc")
}
}
extension HTML {
func blueText() -> some HTML {
modifier(BlueTextModifier())
}
}
You can then use your custom modifier like this:
Text("This text will be blue!")
.blueText()
This text will be blue!
Custom modifiers can also accept parameters to make them more flexible. Here’s how you would create a modifier that accepts a custom color:
struct ColorModifier: HTMLModifier {
let color: String
func body(content: some HTML) -> any HTML {
content.style("color: \(color)")
}
}
extension HTML {
func textColor(_ color: String) -> some HTML {
modifier(ColorModifier(color: color))
}
}
// Usage:
Text("Custom colored text!")
.textColor("#ff6b6b")
Important: Some result builders in Ignite specifically require InlineHTML
or BlockHTML
. In these cases, you’ll need to create additional extensions for these specific types:
extension InlineHTML {
func textColor(_ color: String) -> some InlineHTML {
modifier(ColorModifier(color: color))
}
}
extension BlockHTML {
func textColor(_ color: String) -> some BlockHTML {
modifier(ColorModifier(color: color))
}
}
This ensures your modifiers can be used in all contexts where they make sense.
Created in Swift with Ignite