Skip to content

Commit

Permalink
add isEmpty tag (#118)
Browse files Browse the repository at this point in the history
  • Loading branch information
fananek authored Mar 6, 2023
1 parent 139fcd5 commit 1eddd30
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
10 changes: 10 additions & 0 deletions Sources/LeafKit/LeafSyntax/LeafTag.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public var defaultTags: [String: LeafTag] = [
"uppercased": Uppercased(),
"capitalized": Capitalized(),
"contains": Contains(),
"isEmpty": IsEmpty(),
"date": DateTag(),
"count": Count(),
"comment": Comment(),
Expand Down Expand Up @@ -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()
Expand Down
32 changes: 32 additions & 0 deletions Tests/LeafKitTests/TagTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 = """
Expand Down

0 comments on commit 1eddd30

Please sign in to comment.