我想在freemarker中迭代这样的列表:
<#assign count=myList?size>
<#list 0..count as i>
${myList[i].myProperty}
</#list>
我收到Freemarker的错误说:
freemarker.core.InvalidReferenceException: Expression myList[i].myProperty is
undefined on...
我也尝试过:
${myList[${i}].myProperty}
我知道我能做到
<#list myList as items>
但我想以最重要的方式迭代
答案 0 :(得分:2)
如果你只需要索引,那么你可以这样做:
<#list myList as item>
${item?index} ${item}
</#list>
(请注意?index
仅在2.3.23之后存在;在此之前,请使用旧版item_index
变量。)
如果需要,您还可以使用<#if limit < item_index><#break></#if>
打破循环。
如果你真的需要使用索引进行迭代,请使用<#list 0..<count>
(那里是一个独占结束范围表达式,from ..< to
),因为count
索引处没有项目。 / p>
答案 1 :(得分:1)
您正在获得异常,因为您正在尝试获取索引等于数组大小的项目。假设myList
集合的大小为3,那么使用数值范围序列表达式0..sizeOfMyList
将生成从0
到3
的索引,而索引3
不在这个系列已经开始了。
因此,请使用size-1
从集合中获取所有项目。
<#list 0..count-1 as i>
${myList[i].myProperty}
</#list>
顺便说一句,如果您只需要<#list>
内的当前项目索引,则会有一个特殊变量:variableName_index
。
<#list myList as item>
${item_index}. ${item}
</#list>