List of String in Freemarker
-
09-09-2019 - |
Question
I have a list of string in java code:
List<String> keywords = new ArrayList<String>();
keywords.add("Apple");
keywords.add("Banana");
and I would like to display the keywords using Freemarker: Apple, Banana
How to do that?
PS:
I read through the manual and found some articles suggesting using <#list>
, but the output is:
Apple
Banana
Solution
FreeMarker preserves your spaces (and EOL) but does not add any by itself. So, just put everything in the same line:
<#list myListName as item>${item}</#list>
OTHER TIPS
Since the version 2.3.20 of Freemarker, there is a built-in command for comma-separated lists.
For example, the template:
<#assign colors = ["red", "green", "blue"]>
${colors?join(", ")}
.. will generate:
red, green, blue
If you want a comma-separated list, you can use the following:
<#list seq as x>
${x_index + 1}. ${x}<#if x_has_next>,</#if>
</#list>
see: http://freemarker.org/docs/ref_directive_list.html#pageTopTitle
Since version 2.3.23, you can also use the following code:
<#list users as user>
<div>
${user}<#sep>, </#sep>
</div>
</#list>
Taken from the sep directive.
Freemarker provides some features for whitespace control, see http://freemarker.sourceforge.net/docs/dgui_misc_whitespace.html