FreeMarker 语法 list

一、java 代码

@Test
public void testFreeMarker() throws Exception {
    //1、创建一个模板文件
    //2、创建一个Configuration对象
    Configuration configuration = new Configuration();
    //3、设置模板文件保存的目录
    configuration.setDirectoryForTemplateLoading(new File("E:/workspaces/fw-item-web/src/main/webapp/WEB-INF/ftl"));
    //4、模板文件的编码格式,一般就是utf-8
    configuration.setDefaultEncoding("utf-8");
    //5、加载一个模板文件,创建一个模板对象。
    Template template = configuration.getTemplate("student.ftl");
    //6、创建一个数据集。可以是pojo也可以是map。推荐使用map
    Map data = new HashMap<>();
    
    //添加一个 list
    List<Student> list = new ArrayList<>();
    list.add(new Student(1, "张三", 18));
    list.add(new Student(2, "李四", 19));
    list.add(new Student(3, "王五", 20));
    list.add(new Student(4, "赵六", 21));
    data.put("list", list);
    
    //7、创建一个Writer对象,指定输出文件的路径及文件名。
    Writer out = new FileWriter(new File("E:/freemarker/studentList.html"));
    //8、生成静态页面
    template.process(data, out);
    //9、关闭流
    out.close();
}

 二、student.ftl

<html>
<head>
    <title>student</title>
</head>
<body>
    学生列表:
    <table border="1">
        <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
        </tr>
        <#list list as student>
        <tr>
            <td>${student.id}</td>
            <td>${student.name}</td>
            <td>${student.age}</td>
        </tr>
        </#list>
    </table>

</body>
</html>

三、结果

原文地址:https://www.cnblogs.com/fangwu/p/8696254.html