using error reporter from environment to handle syntax errors

This commit is contained in:
Ilya Puchka
2017-10-07 21:01:28 +02:00
parent 0edb38588d
commit d5f0be959f
3 changed files with 60 additions and 28 deletions

View File

@@ -3,9 +3,15 @@ public struct Environment {
public var extensions: [Extension]
public var loader: Loader?
public var errorReporter: ErrorReporter
public init(loader: Loader? = nil, extensions: [Extension]? = nil, templateClass: Template.Type = Template.self) {
public init(loader: Loader? = nil,
extensions: [Extension]? = nil,
templateClass: Template.Type = Template.self,
errorReporter: ErrorReporter = SimpleErrorReporter()) {
self.templateClass = templateClass
self.errorReporter = errorReporter
self.loader = loader
self.extensions = (extensions ?? []) + [DefaultExtension()]
}
@@ -28,11 +34,21 @@ public struct Environment {
public func renderTemplate(name: String, context: [String: Any]? = nil) throws -> String {
let template = try loadTemplate(name: name)
return try template.render(context)
return try render(template: template, context: context)
}
public func renderTemplate(string: String, context: [String: Any]? = nil) throws -> String {
let template = templateClass.init(templateString: string, environment: self)
return try template.render(context)
return try render(template: template, context: context)
}
func render(template: Template, context: [String: Any]?) throws -> String {
errorReporter.context = ErrorReporterContext(template: template)
do {
return try template.render(context)
} catch {
try errorReporter.report(error: error)
return ""
}
}
}