Freemarker - 如何在同一列表上循环两次?

时间:2011-09-16 18:21:11

标签: freemarker

当在同一个循环上迭代两次时,我收到一个错误:

freemarker.template.SimpleSequence无法投放到java.util.List

First Loop

<#assign peopleMap = context.getpeopleMapByGender()>

<#foreach item in peopleMap["man"] > 
            ${item.first_name!"Unknown"} ${item.last_name!"Unknown"} 
</#foreach>

第二次循环

<#foreach item1 in peopleMap["man"]> 
            ${item1.address!"Unknown"}    
</#foreach>

有没有办法让它发挥作用?我做错了什么?

1 个答案:

答案 0 :(得分:1)

不确定是诚实的。这个简单的例子有效。也许尝试剥离你的模板,看看会发生什么。我认为getpeopleMapByGender()可能是小写p的拼写错误,但这意味着两个循环都无效。

<强> example.ftl

<#assign peopleMap = context.getPeopleMapByGender()>

<#foreach item in peopleMap["man"] > 
            ${item.first_name!"Unknown"} ${item.last_name!"Unknown"} 
</#foreach>

<#foreach item1 in peopleMap["man"]> 
            ${item1.address!"Unknown"}    
</#foreach>

测试类

package grimbo.test.freemarker;

import java.io.File;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

public class DoubleLoop {
    public static void main(String[] args) throws Exception {
        Configuration cfg = new Configuration();
        cfg.setDirectoryForTemplateLoading(new File("./src/test/freemarker"));
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        Template temp = cfg.getTemplate("example.ftl");
        Map root = new HashMap();
        root.put("context", new Context());
        Writer out = new OutputStreamWriter(System.out);
        temp.process(root, out);
        out.flush();
    }

    public static class Context {
        public Map getPeopleMapByGender() {
            Map m = new HashMap();
            m.put("man", Arrays.asList(new Man[] { new Man(), new Man(), new Man() }));
            return m;
        }
    }

    public static class Man {
        private String first_name = "first";

        public String getFirst_name() {
            return first_name;
        }

        public void setFirst_name(String first_name) {
            this.first_name = first_name;
        }
    }
}

<强>输出

        first Unknown 
        first Unknown 
        first Unknown 

        Unknown    
        Unknown    
        Unknown