开发者

Freemarker - how to loop on the same list twice?

When iterating on the same loop twice, I got an error:

freemarker.template.SimpleSequence cannot be cast to java.util.List

First Loop

开发者_如何学编程
<#assign peopleMap = context.getpeopleMapByGender()>

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

Second Loop

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

Is there a way to make it work? What am I doing wrong?


Not sure to be honest. This simple example works. Maybe try and strip your template down and see what happens. I thought getpeopleMapByGender() might be a typo with lowercase p, but that would mean neither loop would work.

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>

Test class

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;
        }
    }
}

Output

        first Unknown 
        first Unknown 
        first Unknown 

        Unknown    
        Unknown    
        Unknown    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜