Broader Frontends
Author : Kazuhiro Hara
Article permalink

Using Custom Attributes with Elementary

Elementary, a template package that can be used with server-side Swift, generates strict HTML. Because of that, attributes are also specified through predefined methods. As a result, it can look as though undefined attributes cannot be used.

For example, you define attributes like this.

h1(.class("my-h1-class")) {
  "Hello Elementary!"
}

The code above specifies the class attribute on the h1 element. Writing it with an implicit member expression is the standard style.

Because of that, it seems like writing an attribute that does not exist in this set would require some ingenuity. I looked at the documentation related to Elementary's HtmlAttributes.

There, I found that the following method exists.

static func custom(name: String, value: String) -> Self {
    HTMLAttribute(name: name, value: value)
}

It looks like custom attributes can be defined by passing the attribute name and value to the custom method. For example, if you want to specify the value hello for the x-data attribute, you can write .custom(name: "x-data", value: "hello").

So custom attributes can be defined like this. When using a library such as Alpine.js, which requires writing its own attributes, the custom method should handle it.

import Elementary
import Vapor
import VaporElementary

...

struct ElementaryPage: HTMLDocument {
    ...

    var body: some HTML {
        main {
            h1(.id("my-h1-id"), .class("my-h1-class"), .custom(name: "x-data", value: "hello")) {
                "Hello Elementary!"
            }
        }
    }
}

Running the code above produces an HTML response like this.

<!DOCTYPE html>
<html>
  <head>
    <title>Elementary</title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <main>
      <h1 id="my-h1-id" class="my-h1-class" x-data="hello">
        Hello Elementary!
      </h1>
    </main>
  </body>
</html>
ElementarySwiftVapor

Share