将 java.lang.Iterable 视为 Freemarker 中的 #list 表达式
我有一个 java.lang.Iterable (实际上是一个 com.google.gson.JsonArray 实例)。
我想使用 freemarker (2.3.16) 枚举列表中的项目。
[#assign sports = controller.sports]
[#-- At this point, sports is bound to a com.google.gson.JsonArray instance. --]
[#list sports as sport]
${sport_index}
[/#list]
我希望避免编写自定义 bean 和 Gson 反序列化器只是为了获得显式的项目集合。使用 Gson(它已经为我将 JSON 字符串反序列化为 JsonObject)然后从该 JsonObject 创建我自己的对象 DAG 对我来说似乎很浪费。
不幸的是,我无法找到一种方法让 Freemarker 将 java.lang.Iterable 视为列表。我得到:
freemarker.template.TemplateException : Expected collection or sequence.
controller.sports evaluated instead to freemarker.ext.beans.XMLStringModel on line 8, column 16 in sports.html.
freemarker.core.TemplateObject.invalidTypeException(line:135)
freemarker.core.IteratorBlock$Context.runLoop(line:190)
freemarker.core.Environment.visit(line:417)
freemarker.core.IteratorBlock.accept(line:102)
freemarker.core.Environment.visit(line:210)
I have a java.lang.Iterable (in fact, a com.google.gson.JsonArray instance).
I would like to enumerate the items in the list using freemarker (2.3.16).
[#assign sports = controller.sports]
[#-- At this point, sports is bound to a com.google.gson.JsonArray instance. --]
[#list sports as sport]
${sport_index}
[/#list]
I would like to avoid having to write a custom bean and Gson deserializer just to have an explicit collection of items. Using Gson (which already deserializes the JSON string to a JsonObject for me) to then create my own DAG of objects from that JsonObject seems wasteful to me.
Unfortunately, I haven't been able to work out a way of getting Freemarker to treat the java.lang.Iterable as a list. I get:
freemarker.template.TemplateException : Expected collection or sequence.
controller.sports evaluated instead to freemarker.ext.beans.XMLStringModel on line 8, column 16 in sports.html.
freemarker.core.TemplateObject.invalidTypeException(line:135)
freemarker.core.IteratorBlock$Context.runLoop(line:190)
freemarker.core.Environment.visit(line:417)
freemarker.core.IteratorBlock.accept(line:102)
freemarker.core.Environment.visit(line:210)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
显式循环迭代器应该可以工作,例如:
Explicitly looping over the iterator should work, e.g.:
您所要做的就是将
JsonArray
上的iterator()
结果添加到上下文中。 Freemarker 足够智能,可以从那里处理它,并且您可以在模板中引用它,就像处理任何其他类似列表的变量一样。All you have to do is add the result of
iterator()
on yourJsonArray
to the context. Freemarker is smart enough to handle it from there, and you can reference it in your template like you do any other list-like variable.Freemarker 现在支持
Iterable
,通过以下方式创建 freemarker 配置:并更新到 2.3.28 版本(我不太确定哪个版本添加了此功能,但 .23 没有它),然后只需实例化您的
Template
并传入该配置即可。Freemarker now supports
Iterable
's by creating your freemarker config via:and updating to the 2.3.28 release (I'm not exactly sure which version added this, but .23 didn't have it), then simply instantiate your
Template
passing in that configuration.