今天用Ajax異步添加評論,加載Freemarker模板引擎,生成模板模塊javascript
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爲須要插入的參數java
關於加載模板位置的方法,借鑑於異步
https://blog.csdn.net/gtlishujie/article/details/52300381ide
我就很少加累述了,關鍵在於獲取文件路徑,文件路徑不對的話,能夠試着輸出而後調試,我的推薦文件加載這個方法工具
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了this