Modifiers

Custom modifiers allow you to create reusable styling and behavior modifications for your HTML elements.

Creating a Custom Modifier

To create a custom modifier, follow these steps:

  1. Create a struct that conforms to HTMLModifier
  2. Implement the required body(content: some HTML) -> any HTML method
  3. Create an extension on HTML to make your modifier easily accessible

Here'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!

Advanced Modifiers

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