Add an include tag

This commit is contained in:
Kyle Fuller
2014-12-29 00:18:58 +00:00
parent 1989c20932
commit fa34c2a98e
7 changed files with 162 additions and 2 deletions

View File

@@ -36,6 +36,7 @@ public class TokenParser {
registerTag("if", IfNode.parse)
registerTag("ifnot", IfNode.parse_ifnot)
registerTag("now", NowNode.parse)
registerTag("include", IncludeNode.parse)
}
/// Registers a new template tag

View File

@@ -11,7 +11,7 @@ import PathKit
// A class for loading a template from disk
public class TemplateLoader {
let paths:[Path]
public let paths:[Path]
public init(paths:[Path]) {
self.paths = paths

View File

@@ -0,0 +1,44 @@
import Foundation
import PathKit
extension String : Error {
public var description:String {
return self
}
}
public class IncludeNode : Node {
public let templateName:String
public class func parse(parser:TokenParser, token:Token) -> TokenParser.Result {
let bits = token.contents.componentsSeparatedByString("\"")
if bits.count != 3 {
return .Error(error:NodeError(token: token, message: "Tag takes one argument, the template file to be included"))
}
return .Success(node:IncludeNode(templateName: bits[1]))
}
public init(templateName:String) {
self.templateName = templateName
}
public func render(context: Context) -> Result {
if let loader = context["loader"] as? TemplateLoader {
if let template = loader.loadTemplate(templateName) {
return template.render(context)
}
let paths:String = join(", ", loader.paths.map { path in
return path.description
})
let error = "Template '\(templateName)' not found in \(paths)"
return .Error(error)
}
let error = "Template loader not in context"
return .Error(error)
}
}