英文:
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"
}
]
如何实现这个?我遇到了以下错误:
英文:
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
答案1
得分: 1
你要查找的表达式是 .vars[user].name
(其中 []
通过动态键进行查找,而 .vars
是一个特殊变量,用于引用所有顶层变量)。然后,你可以将整个内容放入 ${}
中,以便在需要时使用。你还可以使用 <#assign userObj = .vars[user]>
,然后稍后只需编写 userObj.name
和 userObj.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 <#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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论