Add template library loading from FileSystem
This commit is contained in:
23
Sources/HummingbirdMustache/Library+FileSystem.swift
Normal file
23
Sources/HummingbirdMustache/Library+FileSystem.swift
Normal file
@@ -0,0 +1,23 @@
|
||||
import Foundation
|
||||
|
||||
extension HBMustacheLibrary {
|
||||
func loadTemplates(from directory: String, withExtension extension: String = "mustache") {
|
||||
var directory = directory
|
||||
if !directory.hasSuffix("/") {
|
||||
directory += "/"
|
||||
}
|
||||
let extWithDot = ".\(`extension`)"
|
||||
let fs = FileManager()
|
||||
guard let enumerator = fs.enumerator(atPath: directory) else { return }
|
||||
for case let path as String in enumerator {
|
||||
guard path.hasSuffix(extWithDot) else { continue }
|
||||
guard let data = fs.contents(atPath: directory + path) else { continue}
|
||||
let string = String(decoding: data, as: Unicode.UTF8.self)
|
||||
guard let template = try? HBMustacheTemplate(string: string) else { continue }
|
||||
|
||||
// drop ".mustache" from path to get name
|
||||
let name = String(path.dropLast(extWithDot.count))
|
||||
register(template, named: name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
|
||||
public class HBMustacheLibrary {
|
||||
init() {
|
||||
public init() {
|
||||
self.templates = [:]
|
||||
}
|
||||
|
||||
public init(directory: String) {
|
||||
self.templates = [:]
|
||||
self.loadTemplates(from: directory)
|
||||
}
|
||||
|
||||
public func register(_ template: HBMustacheTemplate, named name: String) {
|
||||
templates[name] = template
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user