Rasool Ghafari
Rasool Ghafari

Reputation: 4268

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.

Upvotes: 17

Views: 49289

Answers (3)

manoj kumar c.a
manoj kumar c.a

Reputation: 146

you can use inbuilt index property of FMT: eg:

<#list ['a', 'b', 'c'] as i> ${i?index}: ${i} </#list>

Upvotes: 9

Eddy
Eddy

Reputation: 3723

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>

Upvotes: 4

Duffmaster33
Duffmaster33

Reputation: 1190

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>

Upvotes: 22

Related Questions