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);
    }
    }
    
    
  • 相关阅读:
    创建索引
    列出所有的索引
    查看集群节点api
    集群健康检查api
    mapping 映射
    Elasticsearch 版本控制
    四种常见的 POST 提交数据方式
    HttpPost 传输Json数据并解析
    基本概念
    信用卡年轻消费群体数据分析和洞察报告
  • 原文地址:https://www.cnblogs.com/weiyinfu/p/11102141.html
Copyright © 2011-2022 走看看