From bd31c0c97ff3c2b3416f7c3d53c3b4bea0eef7de Mon Sep 17 00:00:00 2001 From: Pawel Trafimuk Date: Tue, 28 Nov 2023 14:24:58 +0300 Subject: [PATCH] Caching already loaded templates --- Sources/Stencil/Context.swift | 2 +- Sources/Stencil/Environment.swift | 16 +++++++++++----- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/Sources/Stencil/Context.swift b/Sources/Stencil/Context.swift index 21b2a4ef..ac6f86b3 100644 --- a/Sources/Stencil/Context.swift +++ b/Sources/Stencil/Context.swift @@ -9,7 +9,7 @@ public class Context { var dictionaries: [[String: Any?]] /// The context's environment, such as registered extensions, classes, … - public let environment: Environment + public var environment: Environment init(dictionaries: [[String: Any?]], environment: Environment) { self.dictionaries = dictionaries diff --git a/Sources/Stencil/Environment.swift b/Sources/Stencil/Environment.swift index ba0f5064..941b4e58 100644 --- a/Sources/Stencil/Environment.swift +++ b/Sources/Stencil/Environment.swift @@ -14,7 +14,8 @@ public struct Environment { public var trimBehaviour: TrimBehaviour /// Mechanism for loading new files public var loader: Loader? - + /// Already loaded templates + public var loadedTemplates = [String: Template]() /// Basic initializer /// /// - Parameters: @@ -39,9 +40,14 @@ public struct Environment { /// - Parameters: /// - name: Name of the template /// - returns: Loaded template instance - public func loadTemplate(name: String) throws -> Template { - if let loader = loader { - return try loader.loadTemplate(name: name, environment: self) + public mutating func loadTemplate(name: String) throws -> Template { + if let template = loadedTemplates[name] { + return template + } + else if let loader = loader { + let result = try loader.loadTemplate(name: name, environment: self) + loadedTemplates[name] = result + return result } else { throw TemplateDoesNotExist(templateNames: [name], loader: nil) } @@ -66,7 +72,7 @@ public struct Environment { /// - name: Name of the template /// - context: Data for rendering /// - returns: Rendered output - public func renderTemplate(name: String, context: [String: Any] = [:]) throws -> String { + public mutating func renderTemplate(name: String, context: [String: Any] = [:]) throws -> String { let template = try loadTemplate(name: name) return try render(template: template, context: context) }