add contex to include
This commit is contained in:
@@ -3,19 +3,21 @@ import PathKit
|
||||
|
||||
class IncludeNode : NodeType {
|
||||
let templateName: Variable
|
||||
let includeContext: String?
|
||||
|
||||
class func parse(_ parser: TokenParser, token: Token) throws -> NodeType {
|
||||
let bits = token.components()
|
||||
|
||||
guard bits.count == 2 else {
|
||||
throw TemplateSyntaxError("'include' tag takes one argument, the template file to be included")
|
||||
guard bits.count == 2 || (bits.count == 4 && bits[2] == "using") else {
|
||||
throw TemplateSyntaxError("'include' tag requires one argument, the template file to be included. Another optional argument can be used to specify the context that will be passed to the included file, using the format \"using myContext\"")
|
||||
}
|
||||
|
||||
return IncludeNode(templateName: Variable(bits[1]))
|
||||
return IncludeNode(templateName: Variable(bits[1]), includeContext: bits.count == 4 ? bits[3] : nil)
|
||||
}
|
||||
|
||||
init(templateName: Variable) {
|
||||
init(templateName: Variable, includeContext: String? = nil) {
|
||||
self.templateName = templateName
|
||||
self.includeContext = includeContext
|
||||
}
|
||||
|
||||
func render(_ context: Context) throws -> String {
|
||||
@@ -25,7 +27,8 @@ class IncludeNode : NodeType {
|
||||
|
||||
let template = try context.environment.loadTemplate(name: templateName)
|
||||
|
||||
return try context.push {
|
||||
let subContext = includeContext.flatMap{ context[$0] as? [String: Any] }
|
||||
return try context.push(dictionary: subContext) {
|
||||
return try template.render(context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ func testInclude() {
|
||||
let tokens: [Token] = [ .block(value: "include") ]
|
||||
let parser = TokenParser(tokens: tokens, environment: Environment())
|
||||
|
||||
let error = TemplateSyntaxError("'include' tag takes one argument, the template file to be included")
|
||||
let error = TemplateSyntaxError("'include' tag requires one argument, the template file to be included. Another optional argument can be used to specify the context that will be passed to the included file, using the format \"using myContext\"")
|
||||
try expect(try parser.parse()).toThrow(error)
|
||||
}
|
||||
|
||||
@@ -56,6 +56,13 @@ func testInclude() {
|
||||
let value = try node.render(context)
|
||||
try expect(value) == "Hello World!"
|
||||
}
|
||||
|
||||
$0.it("successfully passes context") {
|
||||
let template = Template(templateString: "{% include \"test.html\" using child %}")
|
||||
let context = Context(dictionary: ["child": ["target": "World"]], environment: environment)
|
||||
let value = try template.render(context)
|
||||
try expect(value) == "Hello World!"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user