feat: Add DictionaryLoader to load templates from dictionary

Closes #97
This commit is contained in:
Kyle Fuller
2017-09-07 18:40:21 +01:00
parent 7b9817ed50
commit 000e9a7f1a
4 changed files with 62 additions and 0 deletions

View File

@@ -6,6 +6,8 @@
- Adds `counter0` to for loop context allowing you to get the current index of - Adds `counter0` to for loop context allowing you to get the current index of
the for loop 0 indexed. the for loop 0 indexed.
- Introduces a new `DictionaryLoader` for loading templates from a Swift
Dictionary.
### Bug Fixes ### Bug Fixes

View File

@@ -75,6 +75,33 @@ public class FileSystemLoader: Loader, CustomStringConvertible {
} }
public class DictionaryLoader: Loader {
public let templates: [String: String]
public init(templates: [String: String]) {
self.templates = templates
}
public func loadTemplate(name: String, environment: Environment) throws -> Template {
if let content = templates[name] {
return environment.templateClass.init(templateString: content, environment: environment, name: name)
}
throw TemplateDoesNotExist(templateNames: [name], loader: self)
}
public func loadTemplate(names: [String], environment: Environment) throws -> Template {
for name in names {
if let content = templates[name] {
return environment.templateClass.init(templateString: content, environment: environment, name: name)
}
}
throw TemplateDoesNotExist(templateNames: names, loader: self)
}
}
extension Path { extension Path {
func safeJoin(path: Path) throws -> Path { func safeJoin(path: Path) throws -> Path {
let newPath = self + path let newPath = self + path

View File

@@ -29,4 +29,27 @@ func testTemplateLoader() {
try expect(try environment.loadTemplate(name: "../LoaderSpec.swift")).toThrow() try expect(try environment.loadTemplate(name: "../LoaderSpec.swift")).toThrow()
} }
} }
describe("DictionaryLoader") {
let loader = DictionaryLoader(templates: [
"index.html": "Hello World"
])
let environment = Environment(loader: loader)
$0.it("errors when a template cannot be found") {
try expect(try environment.loadTemplate(name: "unknown.html")).toThrow()
}
$0.it("errors when an array of templates cannot be found") {
try expect(try environment.loadTemplate(names: ["unknown.html", "unknown2.html"])).toThrow()
}
$0.it("can load a template from a known templates") {
_ = try environment.loadTemplate(name: "index.html")
}
$0.it("can load a known template from a collection of templates") {
_ = try environment.loadTemplate(names: ["unknown.html", "index.html"])
}
}
} }

View File

@@ -73,6 +73,16 @@ on the file system.
FileSystemLoader(bundle: [Bundle.main]) FileSystemLoader(bundle: [Bundle.main])
DictionaryLoader
~~~~~~~~~~~~~~~~
Loads templates from a dictionary.
.. code-block:: swift
DictionaryLoader(templates: ["index.html": "Hello World"])
Custom Loaders Custom Loaders
~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~