Add index filter
This commit is contained in:
@@ -2,10 +2,12 @@
|
|||||||
struct HBMustacheContext: HBMustacheMethods {
|
struct HBMustacheContext: HBMustacheMethods {
|
||||||
var first: Bool
|
var first: Bool
|
||||||
var last: Bool
|
var last: Bool
|
||||||
|
var index: Int
|
||||||
|
|
||||||
init(first: Bool = false, last: Bool = false) {
|
init(first: Bool = false, last: Bool = false) {
|
||||||
self.first = first
|
self.first = first
|
||||||
self.last = last
|
self.last = last
|
||||||
|
self.index = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func runMethod(_ name: String) -> Any? {
|
func runMethod(_ name: String) -> Any? {
|
||||||
@@ -14,6 +16,8 @@ struct HBMustacheContext: HBMustacheMethods {
|
|||||||
return self.first
|
return self.first
|
||||||
case "last":
|
case "last":
|
||||||
return self.last
|
return self.last
|
||||||
|
case "index":
|
||||||
|
return self.index
|
||||||
default:
|
default:
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,3 +39,14 @@ extension Dictionary: HBMustacheMethods {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
extension Int: HBMustacheMethods {
|
||||||
|
func runMethod(_ name: String) -> Any? {
|
||||||
|
switch name {
|
||||||
|
case "plus1":
|
||||||
|
return self + 1
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ extension Sequence {
|
|||||||
string += template.render(currentObject, context: context)
|
string += template.render(currentObject, context: context)
|
||||||
currentObject = object
|
currentObject = object
|
||||||
context.first = false
|
context.first = false
|
||||||
|
context.index += 1
|
||||||
}
|
}
|
||||||
|
|
||||||
context.last = true
|
context.last = true
|
||||||
|
|||||||
@@ -33,6 +33,21 @@ final class MethodTests: XCTestCase {
|
|||||||
""")
|
""")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func testIndex() throws {
|
||||||
|
let template = try HBMustacheTemplate(string: """
|
||||||
|
{{#repo}}
|
||||||
|
<b>{{#index()}}{{plus1(.)}}) {{/}}{{ name }}</b>
|
||||||
|
{{/repo}}
|
||||||
|
""")
|
||||||
|
let object: [String: Any] = ["repo": [["name": "resque"], ["name": "hub"], ["name": "rip"]]]
|
||||||
|
XCTAssertEqual(template.render(object), """
|
||||||
|
<b>1) resque</b>
|
||||||
|
<b>2) hub</b>
|
||||||
|
<b>3) rip</b>
|
||||||
|
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
func testReversed() throws {
|
func testReversed() throws {
|
||||||
let template = try HBMustacheTemplate(string: """
|
let template = try HBMustacheTemplate(string: """
|
||||||
{{#reversed(repo)}}
|
{{#reversed(repo)}}
|
||||||
|
|||||||
Reference in New Issue
Block a user