From 1223efbc7e4585b760d4ae538a5838199793f6ca Mon Sep 17 00:00:00 2001 From: Ilya Puchka Date: Sun, 24 Dec 2017 20:11:46 +0100 Subject: [PATCH] fix(default): Check for wrapped nil in filter (#162) --- CHANGELOG.md | 1 + Sources/Filters.swift | 3 ++- Tests/StencilTests/FilterSpec.swift | 8 ++++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9551785d..fd8e81f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ### Bug Fixes - Fixed rendering `{{ block.super }}` with several levels of inheritance +- Fixed checking dictionary values for nil in `default` filter ## 0.10.1 diff --git a/Sources/Filters.swift b/Sources/Filters.swift index dd78ff42..f84a5341 100644 --- a/Sources/Filters.swift +++ b/Sources/Filters.swift @@ -11,7 +11,8 @@ func lowercase(_ value: Any?) -> Any? { } func defaultFilter(value: Any?, arguments: [Any?]) -> Any? { - if let value = value { + // value can be optional wrapping nil, so this way we check for underlying value + if let value = value, String(describing: value) != "nil" { return value } diff --git a/Tests/StencilTests/FilterSpec.swift b/Tests/StencilTests/FilterSpec.swift index 61e2dda8..ded572c0 100644 --- a/Tests/StencilTests/FilterSpec.swift +++ b/Tests/StencilTests/FilterSpec.swift @@ -136,6 +136,14 @@ func testFilter() { let result = try template.render(Context(dictionary: [:])) try expect(result) == "Hello World" } + + $0.it("checks for underlying nil value correctly") { + let template = Template(templateString: "Hello {{ user.name|default:\"anonymous\" }}") + let nilName: String? = nil + let user: [String: Any?] = ["name": nilName] + let result = try template.render(Context(dictionary: ["user": user])) + try expect(result) == "Hello anonymous" + } } describe("join filter") {