循环变量内建函数
- counter
- has_next
- index
- is_even_item
- is_first
- is_last
- is_odd_item
- item_cycle
- item_parity
- item_parity_cap
这些内建函数只能用于list 和 items 指令 的循环变量 (也可以用于已经废弃的 foreach 指令)。 下面是一些说明(loopVar?index 在可以列表的值中进行迭代,返回从0开始的索引)
<#-- Note: x is a loop variable -->
<#list ['a', 'b', 'c'] as x>
${x}:${x?index}
</#list>
<#-- a:0 b:1 c:2 -->
当 list 指令不指定循环变量时, 这些内建函数就作用于 items 指令的循环变量
<#list ['a', 'b', 'c']>
<ul>
<#items as x>
<li>${x}:${x?index}</li>
</#items>
</ul>
</#list>
循环变量内建函数仅仅用于循环变量的 名字,
所以它们可以识别相关进行的迭代。它们不读取循环变量的 值。
因此,这就会有解析错误:
<#list ['a', 'b', 'c'] as x>
<#assign y = x>
${y?index} <#-- ERROR: y isn't a loop variable -->
</#list>
1.counter
返回当前迭代(由循环变量名称识别)从1开始的索引(区分index从数组下标0开始)
<#list ['a', 'b', 'c'] as i>
${i?counter}: ${i}
<br>
</#list>
<#list ['a', 'b', 'c'] as i>
${i?index}: ${i}
<br>
</#list>
2.has_next:辨别循环项是否是当前迭代(由循环变量名称识别)的最后一项
是否还有下一个。最后一个时返回false 其它的为true
<#list ['a', 'b', 'c'] as i>${i?has_next?c} </#list>
有时候,最后一项在显示的时候可能要做特殊处理,例如不加逗号
<#list ["hello","world"] as word>
<span>${word}</span><#if word_has_next>,+</#if></#list>
[注意]:如果需要对该内建函数取反,请使用 var?is_last 来代替 !var?has_next, 因为它的可读性更强
当不得不显示介于每个迭代项(但不能在第一项之前或最后一项之后) 之间的一些内容时,可以使用 sep更方便
<#assign users = ["alice", "Tom", "Tomas", "prime", "jasper"]>
<#list users as user>
${user}<#sep>,</#sep>
</#list>
3.index:返回当前迭代(由循环变量名称识别)从0开始的索引
<#list ['a', 'b', 'c'] as i>
${i?index}: ${i}
</#list>
4.is_even_item: 辨别循环项是否是当前迭代(由循环变量名称识别)间隔1的奇数项
是否是偶数索引,第0 ,2 , 4…个时返回true
<#list ['a', 'b', 'c', 'd'] as i>${i?is_even_item?c} </#list>
5.is_odd_item: 辨别循环项是否是当前迭代(由循环变量名称识别)间隔1的偶数项
是否是奇数索引,第1,3 , 5…个时返回true
<#list ['a', 'b', 'c', 'd'] as i>${i?is_odd_item?c} </#list>
6.is_first: 辨别循环项是否是当前迭代(由循环变量名称识别)的第一项
第一个返回true
<#list ['a', 'b', 'c'] as i>${i?is_first?c} </#list>
7.is_last:辨别循环项是否是当前迭代(由循环变量名称识别)的最后一项
最后一个返回true
<#list ['a', 'b', 'c'] as i>${i?is_last?c} </#list>
8.item_cycle:这是 item_parity 内建函数 更为通用的版本,这里可以指定何值来代替 “odd” 和 “even”。 它也允许多余两个值来循环
自定义循环索引
<#list ['a', 'b', 'c', 'd', 'e', 'f', 'g'] as i>
<tr class="${i?item_cycle('row1', 'row2', 'row3')}">${i}</tr>
</#list>
一些细节:
- 参数的个数至少是1个,没有上限。
- 参数的类型是任意的,无需只是字符串
- 如果需要"odd" 和 “even”,请使用 item_parity 内建函数 来代替
9.item_parity:基于当前迭代(由循环变量名称识别)间隔为1的索引的奇偶性, 返回字符串值 “odd” 或 “even”,是小写。 这通常用于表格中行间的颜色变换
<#list ['a', 'b', 'c', 'd'] as i>
<tr class="${i?item_parity}Row">${i}</tr>
</#list>
10.item_parity_cap:基于当前迭代(由循环变量名称识别)间隔为1的索引的奇偶性, 返回字符串值 “Odd” 或 “Even” (请注意大写)
请使用 item_parity_cap 内建函数 来大写 “Odd” 和 “Even”。
请使用 item_cycle 内建函数 来指定自定义值,或多于两个值
<#list ['a', 'b', 'c', 'd'] as i>
<tr class="row${i?item_parity_cap}">${i}</tr>
</#list>