问题
Is their any way to traverse list item based on their rather than one by one? I want to traverse a list of fields in 1,3,5,7,9 and 2,4,6,8 order. I tried using like this
<#list section.field as field>
<div class="col1">
${field.@label}:<input type="text"/></div>
<#if field_has_next>
<div class="col2">
${field[field_index+1].@label}:<input type="text"/>
</div>
</#if>
</#list>
But it gave me error.
回答1:
This is what ?chunk
is for (http://freemarker.org/docs/ref_builtins_sequence.html#ref_builtin_chunk):
<#list section.field?chunk(2) as row>
<#list row as field>
<div class="col${field_index + 1}">
${field.@label}: <input type="text"/>
</div>
</#list>
</#list>
Otherwise I don't know what error you get with your solution, but surely there's a bug in it that it displays all fields but the last one twice. You could freely play with the indexes with something like
<#assign fields = section.field>
<#assign idx = 0>
<#list 0..999999 as _>
<#if idx == fields?size><#break></#if>
... even column ...
<#assign idx = idx + 1>
<#if idx == fields?size><#break></#if>
... odd column ...
<#assign idx = idx + 1>
</#list>
...
but as you see it doesn't really fit FreeMarker (it's awfully verbose).
来源:https://stackoverflow.com/questions/17723612/freemarker-for-loop