public class Members {
    private String fname;
    private String lname;

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public String getLname() {
        return lname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }
}

public class Greeting {

    Map<String,List<Members>> templateMap;

    public  Map<String, List<Members>> getTemplateMap() {
        return templateMap;
    }
    public void setTemplateMap( Map<String, List<Members>> templateMap) {
        this.templateMap = templateMap;
    }

}


从上面的代码中,如何在html部分的Spring thymeleaf中的templateMap中迭代和显示值?

最佳答案

在controller方法中,您必须将其作为属性添加到Model中,如下所示:model.addAttribute("map",getTemplateMap());(创建Greeting对象以从中获取templateMap)

在您的HTML中,您可以按以下方式进行访问:

<div th:each="stepEntry: ${map}"> // stepEntry now is each entry of your map.
    <p th:text="${stepEntry.key}"></p> // this is the key value of the entry.
    <div th:each="member, iterStat : ${stepEntry.value}"> //this will iterate over the value (which is a list in this case) from the entry.
        <p th:text="${member.fname}"></p> //this prints the fname of each member in the list
    </div>
</div>

10-04 17:16