Java模板引擎FreeMarker系列之十一list下标、索引、长度、初始元素、最后一个元素的获取及应用

如果需要显示当前循环到第几项,可以这样写
<#list ["hello","welcome","hi"] as word>
    <span>${word_index+1},${word}</span></br>
< /#list>

as 后面的那个变量,加上_index,就可以表示当前循环到第几项
结果是:
1,hello
2,welcome
3,hi

有时候,最后一项在显示的时候可能要做特殊处理,怎么判断最后一项?
<#list ["hello","welcome","hi"] as word>
    <span>${word}</span><#if word_has_next>,</#if></#list>
as 后面的那个变量,加上_has_next,就可以判断是否最后一项
结果是:
hello,welcome,hi

如果想在循环中判断到某一项时退出,可以这样做
<#list users as user>
   <span>${user.name}</span>
   <#if user.name == "pxx"><#break></#break>
< /#list>

对一个列表的遍历,如果要对第一个已经最后一个元素做特殊的处理如何的判断呢?

<#list books as book>

<#if book_index = 0>...</#if><!--判断是否是第一个元素-->

<#if !book_has_next>...</#if><!--判断是否是最后一个元素-->

</#list>

item_index 即为当前对象的下标

长度:list.size()

原文地址:https://www.cnblogs.com/hzcya1995/p/13300638.html