今天用Ajax异步添加评论,加载Freemarker模板引擎,生成模板模块
1.新建Freemarker模板
1<li id="${comment.oId}"> 2 <div> 3 <div class="avatar tooltipped tooltipped-n" aria-label="${comment.commentName}" 4 style="background-image: url(${comment.commentThumbnailURL})"></div> 5 <main> 6 <div class="fn-clear"> 7 <#if "http://" == comment.commentURL> 8 ${comment.commentName} 9 <#else> 10 <a class="user-name" href="${comment.commentURL}" target="_blank">${comment.commentName}</a> 11 </#if> 12 <#if comment.isReply> 13 @<a class="user-name" href="/${article.articlePermalink}#${comment.commentOriginalCommentId}" 14 onmouseover="page.showComment(this, '${comment.commentOriginalCommentId}', 23);" 15 onmouseout="page.hideComment('${comment.commentOriginalCommentId}')" 16 >${comment.commentOriginalCommentName}</a> 17 </#if> 18 <time class="ft-gray">${comment.commentDate?string("yyyy-MM-dd HH:mm")}</time> 19 20 <#if article.articleCommentable==1> 21 <a class="reply-btn" href="javascript:replyTo('${comment.oId}')">${replyLabel}</a> 22 </#if> 23 </div> 24 <div class="content-reset"> 25 ${comment.commentContent} 26 </div> 27 </main> 28 </div> 29</li>
2.新建FreemarkerUtils工具类
1package com.fdzang.mblog.utils; 2 3import freemarker.template.Configuration; 4import freemarker.template.Template; 5import freemarker.template.TemplateException; 6import freemarker.template.TemplateExceptionHandler; 7 8import java.io.File; 9import java.io.IOException; 10import java.io.StringWriter; 11import java.util.Map; 12 13public class FreemarkerUtils { 14 public static String getTemplate(String template, Map<String,Object> map) throws IOException, TemplateException { 15 Configuration cfg = new Configuration(Configuration.VERSION_2_3_28); 16 String templatePath = FreemarkerUtils.class.getResource("/").getPath()+"/templates"; 17 cfg.setDirectoryForTemplateLoading(new File(templatePath)); 18 cfg.setDefaultEncoding("UTF-8"); 19 cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); 20 cfg.setLogTemplateExceptions(false); 21 cfg.setWrapUncheckedExceptions(true); 22 Template temp = cfg.getTemplate(template); 23 StringWriter stringWriter = new StringWriter(); 24 temp.process(map, stringWriter); 25 return stringWriter.toString(); 26 } 27}
template为模板的名称,Map为需要插入的参数
关于加载模板位置的方法,借鉴于
https://blog.csdn.net/gtlishujie/article/details/52300381
我就不多加累述了,关键在于获取文件路径,文件路径不对的话,可以试着输出然后调试,个人推荐文件加载这个方法
3.Controller层的方法
1Map<String,Object> map=new HashMap<>(); 2map.put("article",article); 3map.put("comment",comment); 4map.put("replyLabel","回复"); 5String cmtTpl= FreemarkerUtils.getTemplate("common-comment.ftl",map); 6result.setCmtTpl(cmtTpl);
定义好Map参数,指定加载的模板引擎,就可以得到解析后的HTML了