Skip to content

Commit

Permalink
Merge pull request #1 from pavel-trafimuk/master
Browse files Browse the repository at this point in the history
Caching loaded template lines to improve performance
  • Loading branch information
art-divin authored Dec 20, 2023
2 parents ea58733 + 018898d commit 03a1dca
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
2 changes: 1 addition & 1 deletion Sources/Stencil/Context.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 11 additions & 5 deletions Sources/Stencil/Environment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)
}
Expand All @@ -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)
}
Expand Down

0 comments on commit 03a1dca

Please sign in to comment.