Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get comma between Freemarker list

I am iterating a java list in freemarker , but I want commas in between the words. Here's my code

<#list key_list[key] as value >${value?js_string}, </#list>

This gives me output as

a,b,c,d,

I want the output in this format:(No comma in the end)

a,b,c,d

How can I get that

like image 284
user3561824 Avatar asked Apr 27 '14 21:04

user3561824


People also ask

How do you create a list on FreeMarker?

FreeMarker doesn't support modifying collections. But if you really want to do this in FreeMarker (as opposed to in Java), you can use sequence concatenation: <#assign myList = myList + [newItem]> . Here you create a new sequence that wraps the two other sequences.

How do Freemarkers multiply?

Arithmetical calculations So the operators are: Addition: + Subtraction: - Multiplication: *

What language is FreeMarker?

FreeMarker is a template engine, written in Java, and maintained by the Apache Foundation. We can use the FreeMarker Template Language, also known as FTL, to generate many text-based formats like web pages, email, or XML files.

What is eval in FreeMarker?

eval. This built-in evaluates a string as an FTL expression. For example "1+2"? eval returns the number 3. (To render a template that's stored in a string, use the interpret built-in instead.)


3 Answers

If you use FreeMarker version 2.3.23 or higher, sep tag will work for you:

<#list users as user>
    ${user}<#sep>, </#sep>
</#list>

OR even shorter than that:

<#list users as user>${user}<#sep>, </#list>
like image 120
Sanket Mehta Avatar answered Oct 18 '22 00:10

Sanket Mehta


You have to include an <#if value_has_next>,</#if> statement.

This may help:

<#assign seq = ["winter", "spring", "summer", "autumn"]>
<#list seq as x>
  ${x_index + 1}. ${x}<#if x_has_next>,</#if>
</#list>  

will output:

  1. winter,
  2. spring,
  3. summer,
  4. autumn

See this and more examples at:

http://freemarker.org/docs/ref_directive_list.html

like image 36
Andres Avatar answered Oct 17 '22 23:10

Andres


This will give exact result

Actually you need to create a variable , then append data in it. e.g <#assign result =""/>

<#assign result =""/>
<#assign seq = ["a", "b", "c", "d"]> // test data for checking output format
<#list seq as x>  
 <#assign result = result+"${x}"/> 
 <#if x_has_next>
  <#assign result = result+","/>
 </#if>
</#list>  
${result}

Result

a,b,c,d
like image 1
Asif Bhutto Avatar answered Oct 17 '22 23:10

Asif Bhutto