Reputation: 664
I want to iterate over a list like this in freemarker:
<#assign count=myList?size>
<#list 0..count as i>
${myList[i].myProperty}
</#list>
I get an error from Freemarker saying:
freemarker.core.InvalidReferenceException: Expression myList[i].myProperty is
undefined on...
I have also tried:
${myList[${i}].myProperty}
I know I can do
<#list myList as items>
But I want to iterate over like in the top way
Upvotes: 1
Views: 1157
Reputation: 31112
In case you just need the index, then you can do:
<#list myList as item>
${item?index} ${item}
</#list>
(Note that ?index
only exists since 2.3.23; before that, use the legacy item_index
variable.)
You can also use <#if limit < item_index><#break></#if>
to break out of the loop, if that's what's needed.
If you really need to iterate with an index, use <#list 0..<count>
(that's an exclusive-end range expression there, from ..< to
), as there's no item at the count
index.
Upvotes: 2
Reputation: 24396
You are getting an exception because you are trying to get item with index equal to the size of the array. Lets say the size of myList
collection is 3 then using numerical range sequence expression 0..sizeOfMyList
will produce indexes from 0
to 3
, and index 3
is out of bound for this collection.
So use size-1
to get all items from the collection.
<#list 0..count-1 as i>
${myList[i].myProperty}
</#list>
BTW if you just need an index of current item inside <#list>
there is special variable for that: variableName_index
.
<#list myList as item>
${item_index}. ${item}
</#list>
Upvotes: 1