Freemarker 加载模板目录的方法

xiaoxiao2021-02-28  40

Freemarker提供了3种加载模板目录的方法,使用Configuration类加载模板

3种方法分别是:

public void setClassForTemplateLoading(Class clazz, String pathPrefix);

public void setDirectoryForTemplateLoading(File dir) throws IOException;

public void setServletContextForTemplateLoading(Object servletContext, String path);

第一种示例(适合加载Jar包内的资源):

Configuration cfg = new Configuration(); cfg.setClassForTemplateLoading(FreemarkerUtil.class, "/template"); cfg.getTemplate("Base.ftl");

第二种示例(适合加载文件路径):

Configuration cfg = new Configuration(); cfg.setDirectoryForTemplateLoading(new File("/home/user/template")); cfg.getTemplate("Base.ftl");

这样就获得了/home/user/template/Base.ftl这个模板文件。

也适合加载Runtime时的模板路径

Configuration cfg = new Configuration(); // 指定FreeMarker模板文件的位置 try { cfg.setDirectoryForTemplateLoading(new File(CustomerGenerator.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "com/boot/admin/generator/templates")); cfg.getTemplate("Base.ftl"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }第三种示例( 基于WebRoot下的): Configuration cfg = new Configuration(); // 指定FreeMarker模板文件的位置 try { cfg.setServletContextForTemplateLoading(getServletContext(), "/ftl");就是 /WebRoot/ftl目录 cfg.getTemplate("Base.ftl"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }

转载请注明原文地址: https://www.6miu.com/read-2622037.html

最新回复(0)