SpringBoot集成FreeMarker,此工具可以借助FreeMarker渲染一个模板文件
引入pom.xml
<properties>
<!-- 模板引擎 -->
<freemarker.version>2.3.31</freemarker.version>
</properties>
<!-- 模板引擎 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency>
工具类
FreeMarkerUtils.java
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.ui.freemarker.SpringTemplateLoader;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
/**
* @descriptions: 一个模板工具
* @author: xucl
* @date: 2020/07/01 20:05
* @version: 1.0
*/
@Slf4j
public class FreeMarkerUtils {
private static Configuration cfg = new Configuration(Configuration.getVersion());
static {
cfg.setEncoding(Locale.CHINA, "utf-8");
cfg.setTemplateLoader(new SpringTemplateLoader(new DefaultResourceLoader(),"templates/"));
}
/**
* 获取模板
*
* @param templateName
* @return
*/
public static Template getTpl(String templateName){
try {
Template template = cfg.getTemplate(templateName);
return template;
} catch (Exception e) {
log.error("获取模板失败 {}",templateName,e);
return null;
}
}
/**
* 获取模板写入后的内容
*
* @param templateName
* @param model
* @return
*/
public static Optional<String> getTplText(String templateName, Map<String, Object> model){
try {
Template template = cfg.getTemplate(templateName);
String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
return Optional.ofNullable(text);
} catch (Exception e) {
log.error("获取模板内容失败 {}",templateName,e);
return Optional.empty();
}
}
}
注意事项
- 如果你在springboot项目中是这样写配置,而且是jar包形式运行,可能会出现错误哦!
cfg.setClassForTemplateLoading(FreeMarkerUtils.class, "/templates");
- 本demo中的ftl文件在 resources/templates 中
使用方法
Map<String,Object> model = new HashMap<>();
// .......
// 模板文件后缀可以是 ftl 或者其他
Optional<String> html = FreeMarkerUtils.getTplText("test.html", model);