java Freemarker For 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17723612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Freemarker For loop
提问by Himanshu Yadav
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
他们有什么方法可以根据他们而不是一一遍历列表项吗?我想以 1、3、5、7、9 和 2、4、6、8 的顺序遍历字段列表。我试过这样使用
<#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.
但它给了我错误。
回答by ddekany
This is what ?chunk
is for (http://freemarker.org/docs/ref_builtins_sequence.html#ref_builtin_chunk):
这是?chunk
(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).
但正如您所见,它并不适合 FreeMarker(它非常冗长)。