Freemarker静态化加载模板的三种方式

本文介绍了Freemarker提供的三种加载模板目录的方法:通过文件绝对路径、类文件路径及基于WEB服务器路径进行模板加载,并展示了如何同时加载多个模块的模板。

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

3种方法分别是:

public void setDirectoryForTemplateLoading(File dir) throws IOException;

public void setClassForTemplateLoading(Class clazz, String pathPrefix);

public void setServletContextForTemplateLoading(Object servletContext, String path);


第一种 以文件的绝对路径加载

<span style="font-size:14px;">Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File("/opt/user/template"));</span>


第二种 以类文件的路径加载

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

第三种 基于WEB服务器的路径加载

Configuration cfg = new Configuration();
cfg.setServletContextForTemplateLoading(servletContext, "/user/template");


注意一下第二个参数需要以 "/" 开头


同时加载多个模块的模板

//系统模板路径
Configuration cfg = new Configuration();
WebappTemplateLoader wtl =  new WebappTemplateLoader(servletContext,"");
WebappTemplateLoader wt2 =  new WebappTemplateLoader(servletContext,"/"+SystemConstants.SITE_ROOT+"/"+siteCode);
TemplateLoader[] loaders = new TemplateLoader[] { wtl, wt2};
MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);
cfg.setTemplateLoader(mtl);



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值