Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Treat a java.lang.Iterable as a #list expression in Freemarker

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)
like image 391
jabley Avatar asked May 31 '11 17:05

jabley


1 Answers

Explicitly looping over the iterator should work, e.g.:

[#list sports.iterator() as sport]
   ${sport_index}
[/#list]
like image 195
Chaquotay Avatar answered Nov 14 '22 21:11

Chaquotay