Freemarker中list可以是java的数组、List、Collection集合。下面将简单的介绍list的遍历:
Java代码:
ArrayList<String> list = new ArrayList<String>(); list.add("Tom"); list.add("Bill"); list.add("Helen");
Freemarker代码:
# 返回 list 的大小为 3 ${list?size}
Java代码:
public class Animal { private String name; private float price; public Animal(String name, float price) { this.name = name; this.price = price; } ... getter/setter ... } List<Animal> animals = new ArrayList<Animal>(); animals.add(new Animal("snake", 100)); animals.add(new Animal("bird", 120)); animals.add(new Animal("dragon", 999));
Freemarker代码:
<table> <tr> <th>名称</th> <th>价格</th> </tr> <#list animals as being> <tr> <td>${being.name}<td> <td>${being.price}</td> </tr> </#list> </table>
Java代码:
Map<String,Object> myMap = new HashMap<String,Object>(); myMap.put("title", "Map Featch"); myMap.put("version", "v1.2.0");
Freemarker代码:
<select> <#list map?keys as k> <option value="${k}"> ${map[k]} </option> </#list> </select>
_index 是list的一个属性,例如:
List<String> list = new ArrayList<String>(); list.add("Bill"); list.add("Helen");
Freemarker代码:
<#list list as a> <p>${a_index}</p> </#list>
# Java代码 List<String> list = new ArrayList<String>(); list.add("Bill"); list.add("Helen"); # Freemarker代码 ${list[i]}
嵌套时前面要有括号,如下,将字符串变成list,然后取第i个元素的值
# Java代码 String str = "Bill,Helen,Tom"; # Freemarker代码 ${(str?split(","))[i]}
<#list jsskList as jsskVO> <#list kcList as kcVO> <#if kcVO.kch=jsskVO.kch> (kcVO里有编号和名称,而jsskVO里只有编号) ${kcVO.kcm} </#if> </#list> </#list>
<#list list?sort_by("字段") as x> ${x} </#list>
<#list list?sort_by("字段")?reverse as x> ${x} </#list>
<#list userList as user> <#if !user_has_next> 共有${userList?size} 最后一个用户是:${user.userName} </#if> </#list>
参考资料: