Swim – Swift 标记

一个使用 Swift 函数构建器 构建 HTML 文档的 DSL (领域特定语言)。

目前已在 我的个人网站 上使用。

import Swim
import HTML

let myDocument = html(lang: "en-US") {
    head {
        meta(charset: "utf-8", content: "text/html", httpEquiv: "Content-Type")
    }
    body(customAttributes: [ "data-foo": "bar" ]) {
        article(classes: "readme", "modern") {
            header {
                h1 {
                    "This is a great article."
                }
            }

            p {
                "Hello World!"
                br()
                "How are you?"
            }

            p {
                "This is a"
                a(href: "https://swiftlang.cn") { "link to the Swift website" }
                "."
            }
        }
    }
}

通过根据 HTML 规范生成该语言中的所有词汇,我们可以确保只能表达有效的 HTML。

例如,以上代码会生成以下 HTML

<html lang="en-US">
  <head>
    <meta http-equiv="Content-Type" charset="utf-8" content="text/html" />
  </head>
  <body data-foo="bar">
    <article class="readme modern">
      <header>
        <h1>
          This is a great article.
        </h1>
      </header>
      <p>
        Hello World!
        <br/>
        How are you?
      </p>
      <p>
        This is a
        <a href="https://swiftlang.cn">
          link to the Swift website
        </a>
        .
      </p>
    </article>
  </body>
</html>