一个用于 Saga 的渲染器,它使用 Stencil 将 RenderingContext 转换为 String。
它带有一个名为 stencil
的免费函数,该函数接受一个 HTML 模板和一个 Stencil Environment
,并返回一个函数,该函数将 RenderingContext
转换为 String
,然后可以将其插入到 Saga 的 writers 中。
Package.swift
// swift-tools-version:5.5
import PackageDescription
let package = Package(
name: "Example",
platforms: [
.macOS(.v12)
],
dependencies: [
.package(url: "https://github.com/loopwerk/Saga", from: "1.0.0"),
.package(url: "https://github.com/loopwerk/SagaParsleyMarkdownReader", from: "0.5.0"),
.package(url: "https://github.com/loopwerk/SagaStencilRenderer", from: "0.4.0")
],
targets: [
.target(
name: "Example",
dependencies: [
"Saga",
"SagaParsleyMarkdownReader",
"SagaStencilRenderer"
]
),
]
)
main.swift
import Foundation
import Saga
import PathKit
import SagaParsleyMarkdownReader
import SagaStencilRenderer
import Stencil
@main
struct Run {
static func main() async throws {
let saga = try Saga(input: "content", output: "deploy")
try await saga
// All the Markdown files will be parsed to html.
.register(
readers: [.parsleyMarkdownReader()],
itemWriteMode: .keepAsFile,
writers: [
.itemWriter(stencil("page.html", environment: getEnvironment(root: saga.rootPath)))
]
)
// Run the steps we registered above
.run()
// All the remaining files that were not parsed to markdown, so for example images, raw html files and css,
// are copied as-is to the output folder.
.staticFiles()
}
}
func getEnvironment(root: Path) -> Environment {
Environment(loader: FileSystemLoader(paths: [root + "templates"]))
}
请查看示例应用以便试用。
您可以扩展 Environment
,使用您自己的标签和过滤器,请参阅官方 Stencil 文档。
例如
func getEnvironment(root: Path) -> Environment {
let ext = Extension()
ext.registerFilter("url") { (value: Any?) in
guard let item = value as? AnyItem else {
return ""
}
var url = "/" + item.relativeDestination.string
if url.hasSuffix("/index.html") {
url.removeLast(10)
}
return url
}
return Environment(loader: FileSystemLoader(paths: [root + "templates"]), extensions: [ext])
}