Templator

Vapor 3 的模板管理 API

每个人都需要时不时地在他们的应用程序中管理一些模板。Templator 提供了一个与数据库无关的解决方案,并可选择提供一套可配置的 API 端点,允许用户从任何界面管理这些模板。

默认模板源可以托管在远程的 Github 上,并可以随意重新加载/重置。

用法

配置

要设置 API 路由,请执行以下操作(更多关于路由的信息请点击这里

try Templates<PostgreSQLDatabase>.setup(routes: router)

接下来,你需要将 Templator 表/模型添加到你的迁移中

try Templates<PostgreSQLDatabase>.setup(models: &migrationConfig, database: .db)

可选地,你还可以通过一个闭包设置额外的端点身份验证,如下所示

try Templator.Templates<ApiCoreDatabase>.setup(routes: router, permissionCheck: { (routeEnumValue, req) -> EventLoopFuture<Bool> in
    // authenticate
})

要注册所需服务,请运行

try Templates<PostgreSQLDatabase>.setup(services: &services)

除了注册 Leaf 作为模板系统之外,Templates<PostgreSQLDatabase> 也被注册,以便在你的应用程序内部使用。

API 路由

可用的路由如下:

用于修改或创建模板的模型是

{
	"name": "test-template",
	"source": "<h1>Welcome#(name)</h1>",
	"link": "http://link_to_a_remote_template_source.com"
}

在你的应用程序中检索模板非常简单

let templator = try req.make(Templates<ApiCoreDatabase>.self)
let htmlFuture = templator.get(EmailTemplateInvitationHTML.self, data: templateModel, on: req)
return htmlFuture.flatMap(to: View.self) { htmlTemplate in
   /// Use template
}

创建模板

要创建一个新模板,请使你的结构体符合 Source<Database>

/// Basic invitation template
public class EmailTemplateInvitationHTML: Source {
	
	public typealias Database = PostgreSQLDatabase
    
    /// Name of the template
    public static var name: String = "email.invitation.html"
    
    public static var link: String = "https://raw.githubusercontent.com/LiveUI/ApiCore/master/Resources/Templates/email.invitation.html.leaf"
    
    public static var deletable: Bool = false
    
}

如果你想避免为每个模板定义数据库,可以使用一个小技巧,创建一个协议包装器

public protocol TemplateSource: Source where Self.Database == ApiCoreDatabase { }

public class EmailTemplateInvitationPlain: TemplateSource {
    
    /// Name of the template
    public static var name: String = "email.invitation.plain"
    
    public static var link: String = "https://raw.githubusercontent.com/LiveUI/ApiCore/master/Resources/Templates/email.invitation.plain.leaf"
    
    public static var deletable: Bool = false
    
}