Lily
Lily

Reputation: 6022

List of String in Freemarker

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

Upvotes: 19

Views: 34026

Answers (5)

Erik Pragt
Erik Pragt

Reputation: 14627

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.

Upvotes: 8

NickGreen
NickGreen

Reputation: 1752

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

Upvotes: 17

Vincent Cantin
Vincent Cantin

Reputation: 17262

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

Upvotes: 15

skaffman
skaffman

Reputation: 403481

Freemarker provides some features for whitespace control, see http://freemarker.sourceforge.net/docs/dgui_misc_whitespace.html

Upvotes: 1

idrosid
idrosid

Reputation: 8029

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>

Upvotes: 6

Related Questions