Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list items by index in freemarker template?

Is there a way to get list item by index in freemarker template, maybe something like this:

<#assign i = 1>
${fields}[i]

i'm new to freemarker.

like image 302
Rasool Ghafari Avatar asked Apr 08 '15 07:04

Rasool Ghafari


People also ask

How do you create a list in 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 you use the ternary operator in FreeMarker?

When applied to a boolean, the string built-in will act as a ternary operator. It's no very readable as this is not the intended usage of it. It's for formatting boolean values, like Registered: ${registered? string('yes', 'no')} .

What is eval in FreeMarker?

eval returns the number 3. (To render a template that's stored in a string, use the interpret built-in instead.)

How do I comment in FreeMarker template?

Comments: <#-- and --> Comments are similar to HTML comments, but they are delimited by <#-- and -->. Comments will be ignored by FreeMarker, and will not be written to the output.


3 Answers

you can use inbuilt index property of FMT: eg:

<#list ['a', 'b', 'c'] as i> ${i?index}: ${i} </#list>
like image 198
manoj kumar c.a Avatar answered Oct 24 '22 08:10

manoj kumar c.a


Yes, you can easily use the index to get at an item like ${fields[i]}. You might want to loop over the indexes using something like:

<#list 0..fields?size-1 as i>
${fields[i]}
</#list>

Alternatively, you can just list over a sequence without the index like:

<#list fields as field>
${field}
</#list>
like image 38
Duffmaster33 Avatar answered Oct 24 '22 09:10

Duffmaster33


Tested online, the following works well.

Input:

someList = ["2019-12-16", 3]

Template:

<ul> 
   <li>${someList[0]}</li>
   <li>${someList[1]}</li>
</ul>

Output:

<ul> 
   <li>2019-12-16</li>
   <li>3</li>
</ul>
like image 4
Eddy Avatar answered Oct 24 '22 10:10

Eddy