如何创建深度为 n 的 Freemarker 模板?
How do I create a Freemarker template with n depth?
我正在尝试使用 Apache Freemarker 以 n 层深的 json-esque 格式显示一些数据。有了这个未知数,我试图输出类似于下面的内容:
{
"name": "Human",
"type": "object",
"fields": [
{
"name": "weight"
"type": "int"
},
{
"name": "Origin"
"type": "object"
"fields": [
{
"name": "fatherOrigin"
"type": "object"
"fields": [
...
]
},
{
"name": "motherOrigin"
"type": "object"
"fields": [
...
]
}]
}]
}
我想使用一个 while 循环,在伪代码中看起来像这样。
while(1){
if (currType is object) {
print what you know and walk deeper
}else{
print your output and break
}
但是,freemarker 不支持 while 循环。我的替代方法是创建一个列表,该列表的大小大于任何合理的深度 (30)
对于这个问题,这是一个可接受的设计吗?有没有更好的方法来处理它?
谢谢!
确实没有 while
循环。我能想象的最干净的方法是 <#list 0.. as _>...</#list>
,但要注意,0..
只有在 incompatible_improvements
配置设置值足够高的情况下才能正常工作(作为无限系列)。 _
只是一个普通变量,但表示我不关心名称。
但是,一般来说,处理嵌套结构最好用递归来完成。宏和函数支持这一点。然后 #list
-s(如果您完全需要它们的话)通常会检查来自数据模型的实际列表,而不是您作为解决方法构建的某个范围。
我正在尝试使用 Apache Freemarker 以 n 层深的 json-esque 格式显示一些数据。有了这个未知数,我试图输出类似于下面的内容:
{
"name": "Human",
"type": "object",
"fields": [
{
"name": "weight"
"type": "int"
},
{
"name": "Origin"
"type": "object"
"fields": [
{
"name": "fatherOrigin"
"type": "object"
"fields": [
...
]
},
{
"name": "motherOrigin"
"type": "object"
"fields": [
...
]
}]
}]
}
我想使用一个 while 循环,在伪代码中看起来像这样。
while(1){
if (currType is object) {
print what you know and walk deeper
}else{
print your output and break
}
但是,freemarker 不支持 while 循环。我的替代方法是创建一个列表,该列表的大小大于任何合理的深度 (30)
对于这个问题,这是一个可接受的设计吗?有没有更好的方法来处理它?
谢谢!
确实没有 while
循环。我能想象的最干净的方法是 <#list 0.. as _>...</#list>
,但要注意,0..
只有在 incompatible_improvements
配置设置值足够高的情况下才能正常工作(作为无限系列)。 _
只是一个普通变量,但表示我不关心名称。
但是,一般来说,处理嵌套结构最好用递归来完成。宏和函数支持这一点。然后 #list
-s(如果您完全需要它们的话)通常会检查来自数据模型的实际列表,而不是您作为解决方法构建的某个范围。