Freemarker簡單封裝

Freemarker是曾經很流行的一個模板庫,它是一種通用的模板庫,不單單能夠用來渲染html。
模板能夠分爲兩類:html

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

本文展現Freemarker的基本用法,實現一個render(context,templatePath)函數來根據context渲染templatePath路徑下的Freemarker模板。java

maven依賴django

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

Freemarker.javamaven

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);
}
}
相關文章
相關標籤/搜索