尝试遍历项目的选项列表但不打印最后一个选项

时间:2018-03-01 15:20:35

标签: html list loops freemarker

<#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语句,要么告诉它在到达最后一个选项时停止,要么具体告诉它哪个选项内容要停止但是我似乎无法弄清楚如何写它。

2 个答案:

答案 0 :(得分:1)

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 &lt; 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的索引(由...标识)   循环变量名称)目前代表。

答案 1 :(得分:1)

你可以切断列表的最后一项(注意,这会给已经空的列表带来错误):

<#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>