Freemarker中的嵌套表达式

时间:2014-02-01 17:02:04

标签: java html freemarker

我想在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>

但我想以最重要的方式迭代

2 个答案:

答案 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将生成从03的索引,而索引3不在这个系列已经开始了。

因此,请使用size-1从集合中获取所有项目。

<#list 0..count-1 as i>
    ${myList[i].myProperty}
</#list>

顺便说一句,如果您只需要<#list>内的当前项目索引,则会有一个特殊变量:variableName_index

<#list myList as item>
  ${item_index}. ${item}
</#list>