From e7a0738bda6fbb41b34bd884de5447bc7a6c8e3e Mon Sep 17 00:00:00 2001 From: Ilya Puchka Date: Mon, 2 Oct 2017 10:38:50 +0200 Subject: [PATCH] fix(variable): checking values for nil when using mirror (#144) --- CHANGELOG.md | 1 + Sources/Variable.swift | 4 ++++ Tests/StencilTests/IfNodeSpec.swift | 17 +++++++++++++++++ 3 files changed, 22 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c123c4e..712796b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ incorrect amount of arguments. - Fixes a potential crash when using incomplete tokens in a template for example, `{%%}` or `{{}}`. +- Fixes evaluating nil properties as true ## 0.9.0 diff --git a/Sources/Variable.swift b/Sources/Variable.swift index c330d64..239f252 100644 --- a/Sources/Variable.swift +++ b/Sources/Variable.swift @@ -105,6 +105,10 @@ public struct Variable : Equatable, Resolvable { if current == nil { return nil + // mirror returns non-nil value even for nil-containing properties + // so we have to check if its value is actually nil or not + } else if let current = current, String(describing: current) == "nil" { + return nil } } else { return nil diff --git a/Tests/StencilTests/IfNodeSpec.swift b/Tests/StencilTests/IfNodeSpec.swift index f174b6a..c77122f 100644 --- a/Tests/StencilTests/IfNodeSpec.swift +++ b/Tests/StencilTests/IfNodeSpec.swift @@ -253,5 +253,22 @@ func testIfNode() { let result = try renderNodes(nodes, Context(dictionary: ["value": "test"])) try expect(result) == "true" } + + $0.it("evaluates nil properties as false") { + let tokens: [Token] = [ + .block(value: "if instance.value"), + .text(value: "true"), + .block(value: "endif") + ] + + let parser = TokenParser(tokens: tokens, environment: Environment()) + let nodes = try parser.parse() + + struct SomeType { + let value: String? = nil + } + let result = try renderNodes(nodes, Context(dictionary: ["instance": SomeType()])) + try expect(result) == "" + } } }