<#list orderItem.options as option>
<tr>
<td class="order-item-detail">
${option.name} :
</td>
</tr>
<tr>
<td class="order-item-red">
${option.value}
</td>
</tr>
</#list>
上面的代码(在html中)是我正在使用的,以循环一个项目内的选项列表。目前它循环遍历所有选项并打印所有选项。但是我想这样做它不打印此列表中的最终选项。
我有点受限制,因为我必须通过单独的HTML来做到这一点。我假设我需要某种类型的if语句,要么告诉它在到达最后一个选项时停止,要么告诉它具体停止哪个选项内容,但我似乎无法弄清楚如何编写它。
option_index
为您提供当前选项的索引,?size
为您提供长度,您只需要将它们与if语句进行比较
option_index
基于0,因此您需要从大小减去1而不包括最后一项
注意 - 您也可以使用option?index
来获取索引,具体取决于您使用的freemarker版本,但option_index
将适用于较新的freemarker版本以及较旧版本
为了完整性我还将添加?is_last
,信用去ddekany的答案,用法<#if option?is_last>
如果你有一个更新的freemarker版本,if语句就可以这样编写
更新 - 假设Freemarker 2.3.23或更高版本
<#if option?is_last>
....
</#if>
原始答案
<#list orderItem.options as option>
<#if option_index < orderItem.options?size - 1>
<tr>
<td class="order-item-detail">
${option.name} :
</td>
</tr>
<tr>
<td class="order-item-red">
${option.value}
</td>
</tr>
</#if>
</#list>
文档大小
https://freemarker.apache.org/docs/ref_builtins_sequence.html#ref_builtin_size
顺序的子变量数(作为数值)。假设序列具有至少一个子变量,序列s中的最高可能索引是s?size-1(因为第一个子变量的索引是0)。
索引文档
https://freemarker.apache.org/docs/ref_builtins_loop_var.html#ref_builtin_index
返回基于0的索引,其中迭代(由循环变量名称标识)当前成立。
你可以切断列表的最后一项(注意,这会给已经空的列表带来错误):
<#list orderItem.options[0 ..< orderItem.options?size - 1] as x>
...
</#list>
或者,你可以使用?is_last
来检查你是否在最后一项,然后添加一个使用它的嵌套#if
:
<#list orderItem.options as option>
<#if !option?is_last>
...
</#if>
</#list>