Skip to content

Commit

Permalink
Merge pull request #36 from bygri/if-blank-string
Browse files Browse the repository at this point in the history
Proposal: #if(string) to not render if string is blank
  • Loading branch information
tanner0101 authored Dec 9, 2016
2 parents 7d0433b + b7c98bb commit 483e364
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
1 change: 1 addition & 0 deletions Resources/if-empty-string-test.leaf
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
#if(name) { Hello, there! }
9 changes: 6 additions & 3 deletions Sources/Leaf/Tag/Models/If.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,11 @@ public final class If: Tag {
arguments: [Argument],
value: Node?) -> Bool {
guard let value = arguments.first?.value else { return false }
// Existence of bool, evaluate bool. Otherwise, not-nil returns true.
guard let bool = value.bool else { return true }
return bool
// Existence of bool, evaluate bool.
if let bool = value.bool { return bool }
// Empty string value returns false.
if value.string == "" { return false }
// Otherwise, not-nil returns true.
return true
}
}
19 changes: 19 additions & 0 deletions Tests/LeafTests/IfTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ class IfTests: XCTestCase {
("testBasicIfElse", testBasicIfElse),
("testNestedIfElse", testNestedIfElse),
("testIfThrow", testIfThrow),
("testIfEmptyString", testIfEmptyString),
]

func testBasicIf() throws {
Expand Down Expand Up @@ -78,4 +79,22 @@ class IfTests: XCTestCase {
XCTFail("should throw")
} catch If.Error.expectedSingleArgument {}
}

func testIfEmptyString() throws {
let template = try stem.spawnLeaf(named: "if-empty-string-test")
do {
let context = try Node(node: ["name": "name"])
let loadable = Context(context)
let rendered = try stem.render(template, with: loadable).string
let expectation = "Hello, there!"
XCTAssert(rendered == expectation, "have: \(rendered), want: \(expectation)")
}
do {
let context = try Node(node: ["name": ""])
let loadable = Context(context)
let rendered = try stem.render(template, with: loadable).string
let expectation = ""
XCTAssert(rendered == expectation, "have: \(rendered), want: \(expectation)")
}
}
}

0 comments on commit 483e364

Please sign in to comment.