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

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

How to dynamically access objects in ftl?

问题

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

  1. users:
  2. - "u1"
  3. - "u2"
  4. u1:
  5. name: "user1"
  6. age: 25
  7. u2:
  8. name: "user2"
  9. age: 26

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

  1. [
  2. <#list users as user>
  3. {
  4. "username": "${${user}.name}",
  5. "userage": "${${user}.age}"
  6. },
  7. </#list>
  8. ]

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

  1. [
  2. {
  3. "username": "user1",
  4. "userage": "25"
  5. },
  6. {
  7. "username": "user2",
  8. "userage": "26"
  9. }
  10. ]

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

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

英文:

I have my data model stored in yaml as below

  1. users:
  2. - &quot;u1&quot;
  3. - &quot;u2&quot;
  4. u1:
  5. name: &quot;user1&quot;
  6. age: 25
  7. u2:
  8. name: &quot;user2&quot;
  9. age: 26

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

  1. [
  2. &lt;#list users as user&gt;
  3. {
  4. &quot;username&quot;: &quot;${${user}.name}&quot;
  5. &quot;userage&quot;: &quot;${${user}.age}&quot;
  6. },
  7. &lt;/#list&gt;
  8. ]

my final output should look like:

  1. [
  2. {
  3. &quot;username&quot;: &quot;user1&quot;,
  4. &quot;userage&quot;: &quot;25&quot;
  5. },
  6. {
  7. &quot;username&quot;: &quot;user2&quot;,
  8. &quot;userage&quot;: &quot;26&quot;
  9. }
  10. ]

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。)

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

  1. users:
  2. u1:
  3. name: "user1"
  4. age: 25
  5. u2:
  6. name: "user2"
  7. 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:

  1. users:
  2. u1:
  3. name: &quot;user1&quot;
  4. age: 25
  5. u2:
  6. name: &quot;user2&quot;
  7. 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:

确定