Kitura

APIDoc Build Status - Master macOS Linux Apache 2 Slack Status

Kitura-MustacheTemplateEngine

一个使用基于 Mustache 的模板的 Kitura 模板引擎。

Kitura-MustacheTemplateEngine 是 Kitura 模板引擎的一个插件,用于在 Kitura 服务器框架中使用 GRMustache。 这使得使用 Mustache 模板与 Kitura 服务器相结合,创建包含集成 Swift 变量的 HTML 页面变得容易。

Mustache 模板文件

模板文件基本上是带有间隙的 HTML,我们可以在其中插入代码和变量。GRMustache 是一种用于编写模板文件的模板语言,Kitura-MustacheTemplateEngine 可以使用任何标准的 Mustache 模板。

Mustache 手册 提供了有关如何编写 Mustache 模板文件的文档和示例。

默认情况下,Kitura Router 将在 Views 文件夹中查找扩展名为 .mustache 的 Mustache 模板文件。

用法

添加依赖

Kitura-MustacheTemplateEngine 包添加到应用程序 Package.swift 文件中的依赖项中。 将 "x.x.x" 替换为最新的 Kitura-MustacheTemplateEngine 版本

.package(url: "https://github.com/Kitura/Kitura-MustacheTemplateEngine.git", from: "x.x.x")

KituraMustache 添加到你的目标的依赖项中

.target(name: "example", dependencies: ["KituraMustache"]),

导入包

import KituraMustache

示例

以下示例采用使用 kitura init 生成的服务器,并对其进行修改,以从 .mustache 文件提供 Mustache 格式的文本。

在此示例中将编辑的文件如下

<ServerRepositoryName>
├── Package.swift
├── Sources
│    └── Application
│         └── Application.swift
└── Views
    └── Example.mustache

Views 文件夹和 Example.mustache 文件将在本示例稍后创建,因为它们不是由 kitura init 初始化的。

依赖项

将依赖项添加到您的 Package.swift 文件中(如上面添加依赖中所定义)。

Application.swift

Application.swift 文件中,添加以下代码以在 "/winner" 路由上渲染 Example.mustache 模板文件

import KituraMustache

将以下代码添加到 postInit() 函数中

router.add(templateEngine: MustacheTemplateEngine())
router.get("/winner") { _, response, next in
    let  winnings = 10000.0
    let context: [String:Any] =
        ["name" : "Joe Bloggs", "winnings": winnings, "taxed_winnings": winnings * 0.6, "taxable" : true]
    try response.render("Example.mustache", context: context)
    response.status(.OK)
    next()
}

Example.mustache

创建 Views 文件夹并将以下 Mustache 模板代码放入名为 Example.mustache 的文件中

<html>
    Hello {{name}}!
    You have just won {{winnings}} dollars!
    {{#taxable}}
        Well, {{taxed_winnings}} dollars, after taxes.
    {{/taxable}}
</html>

此示例改编自 Mustache 手册 代码,以祝贺比赛的获胜者。

运行应用程序,服务器运行后,转到 https://:8080/winner 以查看渲染的 Mustache 模板。

API 文档

有关更多信息,请访问我们的 API 参考

社区

我们喜欢谈论服务器端 Swift 和 Kitura。 加入我们的 Slack 与团队会面!

许可证

此库在 Apache 2.0 下获得许可。 完整的许可证文本可在 LICENSE 中获得。