Java模板引擎 - FreeMarker


http://freemarker.foofun.cn/

https://freemarker.apache.org/

https://mvnrepository.com/artifact/org.freemarker/freemarker

 

常用代碼

    @Test
    public void deptemp() throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
        
        String templateName = "deptemp.ftl";
        String templatePath = "d:\\template";
        String fileOutPath = "d:\\deptemp.txt";
        
        Map<String, Object> map = initDatamydeptemp();
        
        Configuration config = new Configuration();
        config.setDefaultEncoding("UTF-8");
        config.setDirectoryForTemplateLoading(new File(templatePath));
        Template template = config.getTemplate(templateName);
        template.process(map, new FileWriter(fileOutPath));
        
    }

    private Map<String, Object> initDatamydeptemp() {
        
        List<Emp> emps = new ArrayList<>();
        Emp emp1 = new Emp("1","liubei");
        Emp emp2 = new Emp("2","guanyu");
        emps.add(emp1);
        emps.add(emp2);
        
        List<Dept> depts = new ArrayList<>();
        Dept dept1 = new Dept("1","jishubu",emps);
        Dept dept2 = new Dept("2","caiwubu",emps);
        depts.add(dept1);
        depts.add(dept2);
        
        //創建如下的測試數據
        Map<String, Object> map = new HashMap<String, Object>();
        //列表
        map.put("depts", depts);
        map.put("id", "001");
        return map;
    }

 

常用標簽

1. 單值

<#-- 取單值 -->
${id}

2. 集合

<#-- 取集合 -->
<#list depts as dept>
    部門ID:${dept.id} 
    部門名稱:${dept.name} 
 <#-- 取復合對象 -->
    <#list dept.emps as emp>
        <#-- if判斷 -->
        <#if (emp.name=='liubei')>
            員工ID:${emp.id} 
            員工名稱:${emp.name} 
        </#if>
    </#list>
</#list>


免責聲明!

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



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