Merge pull request #67 from ikesyo/ifnode-evaluate-bool-value
[IfNode] Accept and evaluate a `Bool` value as a valid expression
This commit is contained in:
@@ -29,7 +29,7 @@ public class IfNode : NodeType {
|
||||
public class func parse_ifnot(parser:TokenParser, token:Token) throws -> NodeType {
|
||||
let components = token.components()
|
||||
guard components.count == 2 else {
|
||||
throw TemplateSyntaxError("'ifnot' statements should use the following 'if condition' `\(token.contents)`.")
|
||||
throw TemplateSyntaxError("'ifnot' statements should use the following 'ifnot condition' `\(token.contents)`.")
|
||||
}
|
||||
let variable = components[1]
|
||||
var trueNodes = [NodeType]()
|
||||
@@ -63,6 +63,8 @@ public class IfNode : NodeType {
|
||||
truthy = !result.isEmpty
|
||||
} else if let result = result as? [String:Any] {
|
||||
truthy = !result.isEmpty
|
||||
} else if let result = result as? Bool {
|
||||
truthy = result
|
||||
} else if result != nil {
|
||||
truthy = true
|
||||
}
|
||||
|
||||
@@ -73,14 +73,26 @@ func testIfNode() {
|
||||
}
|
||||
|
||||
$0.describe("rendering") {
|
||||
let context = Context(dictionary: ["items": true])
|
||||
|
||||
$0.it("renders the truth when expression evaluates to true") {
|
||||
let context = Context(dictionary: ["items": true])
|
||||
let node = IfNode(variable: "items", trueNodes: [TextNode(text: "true")], falseNodes: [TextNode(text: "false")])
|
||||
try expect(try node.render(context)) == "true"
|
||||
}
|
||||
|
||||
$0.it("renders the false when expression evaluates to false") {
|
||||
let context = Context(dictionary: ["items": false])
|
||||
let node = IfNode(variable: "items", trueNodes: [TextNode(text: "true")], falseNodes: [TextNode(text: "false")])
|
||||
try expect(try node.render(context)) == "false"
|
||||
}
|
||||
|
||||
$0.it("renders the truth when expression is not nil") {
|
||||
let context = Context(dictionary: ["known": "known"])
|
||||
let node = IfNode(variable: "known", trueNodes: [TextNode(text: "true")], falseNodes: [TextNode(text: "false")])
|
||||
try expect(try node.render(context)) == "true"
|
||||
}
|
||||
|
||||
$0.it("renders the false when expression is nil") {
|
||||
let context = Context(dictionary: [:])
|
||||
let node = IfNode(variable: "unknown", trueNodes: [TextNode(text: "true")], falseNodes: [TextNode(text: "false")])
|
||||
try expect(try node.render(context)) == "false"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user