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.
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.
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')} .
eval returns the number 3. (To render a template that's stored in a string, use the interpret built-in instead.)
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.
you can use inbuilt index property of FMT: eg:
<#list ['a', 'b', 'c'] as i> ${i?index}: ${i} </#list>
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With