Perfect 的 Mustache 模板支持。
此包旨在与 Perfect 一起使用。 它为您的服务器提供 Mustache 模板支持。
首先,将此项目添加为 Package.swift 文件中的依赖项。
.package(url: "https://github.com/PerfectlySoft/Perfect-Mustache.git", from: "3.0.0")
然后,将 "PerfectMustache" 添加到将使用 PerfectMustache 的目标的依赖项列表中。
目标配置示例
targets: [.target(name: "PerfectTemplate", dependencies: ["PerfectHTTPServer", "PerfectMustache"])]
基本用法
let map: [String:Any] = ["fullName":fullName, "uri":uri, "authToken":authToken]
let ctx = MustacheEvaluationContext(templatePath: emailTemplate, map: map)
let result = try ctx.formulateResponse(withCollector: MustacheEvaluationOutputCollector())
以下代码片段说明如何在 URL 处理程序中使用 mustache 模板。 在此示例中,名为“test.html”的模板将位于服务器的 web 根目录中。
{
request, response in
let webRoot = request.documentRoot
mustacheRequest(request: request, response: response, handler: TestHandler(), templatePath: webRoot + "/test.html")
}
您需要实现的模板页面处理程序可能如下所示。
struct TestHandler: MustachePageHandler { // all template handlers must inherit from PageHandler
// This is the function which all handlers must impliment.
// It is called by the system to allow the handler to return the set of values which will be used when populating the template.
// - parameter context: The MustacheWebEvaluationContext which provides access to the HTTPRequest containing all the information pertaining to the request
// - parameter collector: The MustacheEvaluationOutputCollector which can be used to adjust the template output. For example a `defaultEncodingFunc` could be installed to change how outgoing values are encoded.
func extendValuesForResponse(context contxt: MustacheWebEvaluationContext, collector: MustacheEvaluationOutputCollector) {
var values = MustacheEvaluationContext.MapType()
values["value"] = "hello"
/// etc.
contxt.extendValues(with: values)
do {
try contxt.requestCompleted(withCollector: collector)
} catch {
let response = contxt.webResponse
response.status = .internalServerError
response.appendBody(string: "\(error)")
response.completed()
}
}
}
有关更具体的示例,请参阅 UploadEnumerator 示例。
标签支持
此 mustache 模板处理器支持
Partials(局部模板)
所有用于局部模板的文件必须与调用模板位于同一目录中。 此外,所有局部模板文件必须具有 mustache 的文件扩展名,但此扩展名不能包含在局部模板标签本身中。 例如,要包含文件 *foo.mustache* 的内容,您将使用标签 {{> foo }}
。
Encoding(编码)
默认情况下,所有编码标签(即常规标签)都经过 HTML 编码,并且 < & > 实体将被转义。 在您的处理程序中,您可以手动设置 MustacheEvaluationOutputCollector.defaultEncodingFunc
函数来执行您需要的任何编码。 例如,在输出 JSON 数据时,您希望将此函数设置为如下所示的内容
collector.defaultEncodingFunc = {
string in
return (try? string.jsonEncodedString()) ?? "bad string"
}
Lambdas(Lambda表达式)
可以将函数添加到值字典中。 这些函数将被执行,结果将被添加到模板输出中。 这样的函数应该具有以下签名
(tag: String, context: MustacheEvaluationContext) -> String
tag
参数将是标签名称。 例如,标签 {{name}} 将为您提供标签参数的值 "name"。
有关更多信息,请访问 perfect.org。