From 1eddd30f79c116728d67f3f80b2ad677bf6ed232 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Franti=C5=A1ek=20Mik=C5=A1?= <54376466+fananek@users.noreply.github.com> Date: Mon, 6 Mar 2023 22:26:40 +0100 Subject: [PATCH] add isEmpty tag (#118) --- Sources/LeafKit/LeafSyntax/LeafTag.swift | 10 ++++++++ Tests/LeafKitTests/TagTests.swift | 32 ++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/Sources/LeafKit/LeafSyntax/LeafTag.swift b/Sources/LeafKit/LeafSyntax/LeafTag.swift index 09a7d89..c8fa105 100644 --- a/Sources/LeafKit/LeafSyntax/LeafTag.swift +++ b/Sources/LeafKit/LeafSyntax/LeafTag.swift @@ -14,6 +14,7 @@ public var defaultTags: [String: LeafTag] = [ "uppercased": Uppercased(), "capitalized": Capitalized(), "contains": Contains(), + "isEmpty": IsEmpty(), "date": DateTag(), "count": Count(), "comment": Comment(), @@ -67,6 +68,15 @@ struct Contains: LeafTag { } } +struct IsEmpty: LeafTag { + func render(_ ctx: LeafContext) throws -> LeafData { + guard let str = ctx.parameters.first?.string else { + throw "unable to check for empty value unexpected data" + } + return .init(.bool(str.isEmpty)) + } +} + struct DateTag: LeafTag { func render(_ ctx: LeafContext) throws -> LeafData { let formatter = DateFormatter() diff --git a/Tests/LeafKitTests/TagTests.swift b/Tests/LeafKitTests/TagTests.swift index 23eb0bd..101fe1f 100644 --- a/Tests/LeafKitTests/TagTests.swift +++ b/Tests/LeafKitTests/TagTests.swift @@ -117,6 +117,38 @@ class TagTests: XCTestCase { """ try XCTAssertEqual(render(template, ["core": ["Tanner", "Logan", "Gwynne", "Siemen", "Tim"]]), expected) } + + func testIsEmpty() throws { + let template = """ + #if(isEmpty(emptyString)): + This is an empty string. + #endif + """ + + let expected = """ + + This is an empty string. + + """ + try XCTAssertEqual(render(template, ["emptyString": ""]), expected) + } + + func testIsEmptyFalseCase() throws { + let template = """ + #if(isEmpty(nonEmptyString)): + This is an empty string. + #else: + This is not an empty string. + #endif + """ + + let expected = """ + + This is not an empty string. + + """ + try XCTAssertEqual(render(template, ["nonEmptyString": "I'm not empty."]), expected) + } func testContainsTagWithHTML() throws { let template = """