Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to loop though dictionaries #105

Open
ftruter opened this issue Jul 26, 2022 · 0 comments
Open

Add ability to loop though dictionaries #105

ftruter opened this issue Jul 26, 2022 · 0 comments
Labels
enhancement New feature or request help wanted Extra attention is needed

Comments

@ftruter
Copy link

ftruter commented Jul 26, 2022

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 morekey` 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.

@ftruter ftruter added the enhancement New feature or request label Jul 26, 2022
@0xTim 0xTim added the help wanted Extra attention is needed label Jul 26, 2022
pontaoski added a commit to pontaoski/leaf-kit that referenced this issue Aug 27, 2022
… specify the variable name of index for arrays)

Fixes vapor#105.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

2 participants