Add support for Lambdas

This commit is contained in:
Adam Fowler
2021-03-14 08:32:50 +00:00
parent d9bead1553
commit aaf285154d
3 changed files with 17 additions and 0 deletions

View File

@@ -0,0 +1,2 @@
public typealias HBMustacheLambda = (Any, HBMustacheTemplate, HBMustacheLibrary?) -> String

View File

@@ -41,6 +41,8 @@ extension HBMustacheTemplate {
return array.renderSection(with: template, library: library) return array.renderSection(with: template, library: library)
case let bool as Bool: case let bool as Bool:
return bool ? template.render(parent, library: library) : "" return bool ? template.render(parent, library: library) : ""
case let lambda as HBMustacheLambda:
return lambda(parent, template, library)
case .some(let value): case .some(let value):
return template.render(value, library: library) return template.render(value, library: library)
case .none: case .none:

View File

@@ -153,6 +153,19 @@ final class TemplateRendererTests: XCTestCase {
""") """)
} }
func testMustacheManualExample5() throws {
let template = try HBMustacheTemplate(string: """
{{#wrapped}}{{name}} is awesome.{{/wrapped}}
""")
func wrapped(object: Any, template: HBMustacheTemplate, library: HBMustacheLibrary?) -> String {
return "<b>\(template.render(object, library: library))</b>"
}
let object: [String: Any] = ["name": "Willy", "wrapped": wrapped]
XCTAssertEqual(template.render(object), """
<b>Willy is awesome.</b>
""")
}
func testMustacheManualExample6() throws { func testMustacheManualExample6() throws {
let template = try HBMustacheTemplate(string: """ let template = try HBMustacheTemplate(string: """
{{#person?}} {{#person?}}