SpringBoot获取Freemarker模板引擎,生成HTML代码

时间:2022-08-14 22:46:57

今天用Ajax异步添加评论,加载Freemarker模板引擎,生成模板模块

1.新建Freemarker模板

<li id="${comment.oId}">
<div>
<div class="avatar tooltipped tooltipped-n" aria-label="${comment.commentName}"
style="background-image: url(${comment.commentThumbnailURL})"></div>
<main>
<div class="fn-clear">
<#if "http://" == comment.commentURL>
${comment.commentName}
<#else>
<a class="user-name" href="${comment.commentURL}" target="_blank">${comment.commentName}</a>
</#if>
<#if comment.isReply>
@<a class="user-name" href="/${article.articlePermalink}#${comment.commentOriginalCommentId}"
onmouseover="page.showComment(this, '${comment.commentOriginalCommentId}', 23);"
onmouseout="page.hideComment('${comment.commentOriginalCommentId}')"
>${comment.commentOriginalCommentName}</a>
</#if>
<time class="ft-gray">${comment.commentDate?string("yyyy-MM-dd HH:mm")}</time> <#if article.articleCommentable==1>
<a class="reply-btn" href="javascript:replyTo('${comment.oId}')">${replyLabel}</a>
</#if>
</div>
<div class="content-reset">
${comment.commentContent}
</div>
</main>
</div>
</li>

2.新建FreemarkerUtils工具类

package com.fdzang.mblog.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler; import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map; public class FreemarkerUtils {
public static String getTemplate(String template, Map<String,Object> map) throws IOException, TemplateException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
String templatePath = FreemarkerUtils.class.getResource("/").getPath()+"/templates";
cfg.setDirectoryForTemplateLoading(new File(templatePath));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
cfg.setWrapUncheckedExceptions(true);
Template temp = cfg.getTemplate(template);
StringWriter stringWriter = new StringWriter();
temp.process(map, stringWriter);
return stringWriter.toString();
}
}

template为模板的名称,Map为需要插入的参数

关于加载模板位置的方法,借鉴于

https://blog.csdn.net/gtlishujie/article/details/52300381

我就不多加累述了,关键在于获取文件路径,文件路径不对的话,可以试着输出然后调试,个人推荐文件加载这个方法

3.Controller层的方法

Map<String,Object> map=new HashMap<>();
map.put("article",article);
map.put("comment",comment);
map.put("replyLabel","回复");
String cmtTpl= FreemarkerUtils.getTemplate("common-comment.ftl",map);
result.setCmtTpl(cmtTpl);

定义好Map参数,指定加载的模板引擎,就可以得到解析后的HTML了