java 使用freemarker 模板生成html 和字符串

生成字符串:

StringWriter stringWriter = new StringWriter();
//讀取模板的位置在resources 下的templates下contractAgreement.ftl
FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(new File(this.getClass().getClassLoader().getResource("templates/").getPath()));
Configuration configuration = new Configuration(Configuration.VERSION_2_3_26);
configuration.setTemplateLoader(fileTemplateLoader);
Template template = configuration.getTemplate("contractAgreement.ftl", "UTF-8");
Map<String, Object> map = new HashMap<>();
map.put("title", name);
map.put("contentList", list);
template.process(map, stringWriter);
stringWriter.flush();
return StringWriter.toString;

生成html文件:

Configuration configuration = new Configuration(Configuration.VERSION_2_3_26);
        File file = new File(this.getClass().getClassLoader().getResource("templates/").getPath());
        configuration.setDirectoryForTemplateLoading(file);
        configuration.setDefaultEncoding("UTF-8");
        Template template = configuration.getTemplate("contractAgreement.ftl");
        Map<String, Object> map = new HashMap<>();
        map.put("title", name);
        map.put("contentList", list);
        //生成臨時文件夾
        String temporaryUUID = UUID.randomUUID().toString();
        File temporaryFile = new File(this.getClass().getClassLoader().getResource("templates/").getPath() + "/" + temporaryUUID);
        if (!temporaryFile.exists()) {
            temporaryFile.mkdir();
        }
        String filePath = temporaryFile.getPath() + "/" + temporaryUUID + ".html";
        Writer writer = new FileWriter(filePath);
        //生成html
        template.process(map, writer);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章