문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top