Add support for member variables
This commit is contained in:
@@ -89,13 +89,24 @@ extension HBTemplate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getChild(named name: String, from: Any) -> Any? {
|
func getChild(named name: String, from object: Any) -> Any? {
|
||||||
if name == "." { return from }
|
func _getChild(named names: ArraySlice<String>, from object: Any) -> Any? {
|
||||||
if let customBox = from as? HBMustacheParent {
|
guard let name = names.first else { return object }
|
||||||
return customBox.child(named: name)
|
let childObject: Any?
|
||||||
|
if let customBox = object as? HBMustacheParent {
|
||||||
|
childObject = customBox.child(named: name)
|
||||||
|
} else {
|
||||||
|
let mirror = Mirror(reflecting: object)
|
||||||
|
childObject = mirror.getAttribute(forKey: name)
|
||||||
}
|
}
|
||||||
let mirror = Mirror(reflecting: from)
|
guard childObject != nil else { return nil }
|
||||||
return mirror.getAttribute(forKey: name)
|
let names2 = names.dropFirst()
|
||||||
|
return _getChild(named: names2, from: childObject!)
|
||||||
|
}
|
||||||
|
|
||||||
|
if name == "." { return object }
|
||||||
|
let nameSplit = name.split(separator: ".").map { String($0) }
|
||||||
|
return _getChild(named: nameSplit[...], from: object)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -79,4 +79,22 @@ final class TemplateRendererTests: XCTestCase {
|
|||||||
XCTAssertEqual(template2.render(Test(string: "string")), "test ")
|
XCTAssertEqual(template2.render(Test(string: "string")), "test ")
|
||||||
XCTAssertEqual(template2.render(Test(string: nil)), "test *")
|
XCTAssertEqual(template2.render(Test(string: nil)), "test *")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func testDictionarySequence() throws {
|
||||||
|
let template = try HBTemplate("test {{#.}}{{value}}{{/.}}")
|
||||||
|
XCTAssert(template.render(["one": 1, "two": 2]) == "test 12" ||
|
||||||
|
template.render(["one": 1, "two": 2]) == "test 21")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testStructureInStructure() throws {
|
||||||
|
struct SubTest {
|
||||||
|
let string: String?
|
||||||
|
}
|
||||||
|
struct Test {
|
||||||
|
let test: SubTest
|
||||||
|
}
|
||||||
|
|
||||||
|
let template = try HBTemplate("test {{test.string}}")
|
||||||
|
XCTAssertEqual(template.render(Test(test: .init(string: "sub"))), "test sub")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user