Description
Looping through arrays is already possible via the #for( something in array ):
syntax. But I often need to loop through dictionaries. In my projects I often have [UUID: Codable]
or [String: Codable]
structures.
I would like to be able to write
struct Person : Codable {
var name: String
// ...more props
}
let persons : [String: Person] = [
"a": Person(name: "tanner"),
"b": Person(name: "ziz"),
"c": Person(name: "vapor")
]
let template = """
#for(person in persons):
#(key): #(person.name) index=#(index) last=#(isLast) first=#(isFirst)
#endfor
"""
render(template, ["persons": persons])
Should render
a: tanner index=0 last=false first=true
b: ziz index=1 last=false first=false
c: vapor index=2 last=true first=false
Leaf's current #for
implementation already exposes additional local in-loop variables index
, isFirst
and 'isLastand my proposal adds just one more
key` variable.
Alternatively extending the loop syntax to #for( (key, person) in persons )
would have provided control over the name of the in-loop variables, and this feels more "Swift-like" yet breaks with Leaf-kit tradition.
Another alternative was to loop through the keys instead of the values, e.g. #for( key in persons ):
but this will require repeated dictionary lookups when interpolating values, e.g.
#for(key in persons):
#(key): #(persons[key].name) #(persons[key].address) #(persons[key].tel)
#endfor
This option feels more like Javascript or Python but the repeated dictionary looks are tedious to write and has a runtime performance penalty.
Activity