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>

三、結果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM