Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Caching loaded template lines to improve performance #345

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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