Search code examples
templatesyamlfreemarker

How to dynamically access objects in ftl?


I have my data model stored in yaml as below

users:
  - "u1"
  - "u2"

u1:
  name: "user1"
  age: 25

u2:
  name: "user2"
  age: 26

I am trying to use the below template (ftl) to generate user records

[
    <#list users as user>
    {
        "username": "${${user}.name}"
        "userage": "${${user}.age}"
    },
    </#list>
]

my final output should look like:

[
    {
        "username": "user1",
        "userage": "25"
    },
    {
        "username": "user2",
        "userage": "26"
    }
]

How to achieve this? I am getting below error

enter image description here


Solution

  • The expression you are looking for is .vars[user].name (where [] does the lookup by a dynamic key, and .vars is a special variable to refer to all your top-level variables). Then you can put that whole thing into ${} where that's needed. You can also do <#assign userObj = .vars[user]>, and then later just write userObj.name, and userObj.age. (Though, regrading the name choices, I would use userId instead of user, and user instead of userObj.)

    Last not least, the data-model should just be like this, if possible, and then everything is simpler, and less confusing:

    users:
      u1:
        name: "user1"
        age: 25
    
      u2:
        name: "user2"
        age: 26
    

    So then you can write something like users.u1.age. If the user ID is dynamic, and let's say it's in the userId variable, then you can write users[userId].age.