zoukankan      html  css  js  c++  java
  • 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);
    }
    }
    
    
  • 相关阅读:
    CUDA运行时 Runtime(一)
    CUDA C++程序设计模型
    CUDA C++编程手册(总论)
    深度学习到底有哪些卷积?
    卷积神经网络去雾去雨方法
    马斯克如何颠覆航天? 1/5385成本,c++和python编程!
    CUDA 9中张量核(Tensor Cores)编程
    利用表达式调用全局变量计算出错原因
    述函数的作用,浏览器执行函数的过程
    表达式的差异和相同点
  • 原文地址:https://www.cnblogs.com/weiyinfu/p/11102141.html
Copyright © 2011-2022 走看看