• Freemarker简单封装


    Freemarker是曾经很流行的一个模板库,它是一种通用的模板库,不仅仅可以用来渲染html。
    模板可以分为两类:

    • 只能生成特殊类型文件的模板,如jinja、django、Thymeleaf、jade等模板只能生成HTML
    • 通用型模板,如mustache、Freemarker

    本文展示Freemarker的基本用法,实现一个render(context,templatePath)函数来根据context渲染templatePath路径下的Freemarker模板。

    maven依赖

            <dependency>
                <groupId>org.freemarker</groupId>
                <artifactId>freemarker</artifactId>
                <version>2.3.28</version>
            </dependency>
    

    Freemarker.java

    import freemarker.template.Configuration;
    import freemarker.template.Template;
    import freemarker.template.TemplateException;
    import freemarker.template.Version;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.StringWriter;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.HashMap;
    import java.util.Map;
    
    public class Freemarker {
    Configuration conf;
    
    public Freemarker(Path templatePath) {
        conf = new Configuration(new Version(2, 3, 23));
        conf.setDefaultEncoding("utf8");
        try {
            conf.setDirectoryForTemplateLoading(templatePath.toFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public void render(Object obj, String templatePath, PrintWriter out) {
        try {
            Template template = conf.getTemplate(templatePath);
            template.process(obj, out);
            out.flush();
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
    }
    
    public String render(Object obj, String templatePath) {
        StringWriter cout = new StringWriter();
        PrintWriter writer = new PrintWriter(cout);
        render(obj, templatePath, writer);
        writer.close();
        return cout.toString();
    }
    
    public static void main(String[] args) throws IOException, TemplateException {
        Map<String, Integer> ma = new HashMap<>();
        ma.put("one", 1);
        ma.put("two", 2);
        ma.put("three", 3);
        String ans = new Freemarker(Paths.get(".")).render(ma, "haha.ftl");
        System.out.println(ans);
    }
    }
    
    
  • 相关阅读:
    前端代码美化的艺术
    CSS3 简单的砸金蛋样式
    为什么 VS Code 能迅速占领 JavaScript 开发者社区
    了解并使用 CSS 中的 rem 单位
    CSS中一些利用伪类、伪元素和相邻元素选择器的技巧
    SVG入门指南
    PAT 1035 Password [字符串][简单]
    生信学习-二代测序知乎专栏总结[转]
    PAT 1119 Pre- and Post-order Traversals [二叉树遍历][难]
    生信笔记-mooc【武大】
  • 原文地址:https://www.cnblogs.com/weiyinfu/p/11102141.html
Copyright © 2020-2023  润新知