如何在ftl中动态访问对象?

huangapple go评论87阅读模式
英文:

How to dynamically access objects in ftl?

问题

我已经将我的数据模型存储在以下的YAML文件中:

users:
  - "u1"
  - "u2"

u1:
  name: "user1"
  age: 25

u2:
  name: "user2"
  age: 26

我尝试使用以下的模板(FTL)来生成用户记录:

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

我的最终输出应该如下所示:

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

如何实现这个?我遇到了以下错误:

如何在ftl中动态访问对象?

英文:

I have my data model stored in yaml as below

users:
  - &quot;u1&quot;
  - &quot;u2&quot;

u1:
  name: &quot;user1&quot;
  age: 25

u2:
  name: &quot;user2&quot;
  age: 26

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

[
    &lt;#list users as user&gt;
    {
        &quot;username&quot;: &quot;${${user}.name}&quot;
        &quot;userage&quot;: &quot;${${user}.age}&quot;
    },
    &lt;/#list&gt;
]

my final output should look like:

[
    {
        &quot;username&quot;: &quot;user1&quot;,
        &quot;userage&quot;: &quot;25&quot;
    },
    {
        &quot;username&quot;: &quot;user2&quot;,
        &quot;userage&quot;: &quot;26&quot;
    }
]

How to achieve this? I am getting below error

如何在ftl中动态访问对象?

答案1

得分: 1

你要查找的表达式是 .vars[user].name(其中 [] 通过动态键进行查找,而 .vars 是一个特殊变量,用于引用所有顶层变量)。然后,你可以将整个内容放入 ${} 中,以便在需要时使用。你还可以使用 &lt;#assign userObj = .vars[user]&gt;,然后稍后只需编写 userObj.nameuserObj.age。(不过,关于名称选择,我建议使用 userId 代替 user,以及 user 代替 userObj。)

最后,如果可能的话,数据模型应该像这样简单明了:

users:
  u1:
    name: "user1"
    age: 25

  u2:
    name: "user2"
    age: 26

这样你就可以像这样编写 users.u1.age。如果用户ID是动态的,假设它存储在 userId 变量中,那么你可以编写 users[userId].age

英文:

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 &lt;#assign userObj = .vars[user]&gt;, 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: &quot;user1&quot;
    age: 25

  u2:
    name: &quot;user2&quot;
    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.

huangapple
  • 本文由 发表于 2023年2月10日 16:43:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定