springboot 使用FreeMarker模板

在spring boot中使用FreeMarker模板非常简单方便,只需要简单几步就行:

1、引入依赖:

  1. <dependency>  
  2.     <groupId>org.springframework.boot</groupId>  
  3.     <artifactId>spring-boot-starter-freemarker</artifactId>  
  4. </dependency>  


2、创建模板:

 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <body>  
  4. <h4>亲爱的${toUserName},你好!</h4>  
  5.   
  6. <style="color:blue;"> ${message}</p>  
  7.   
  8. 祝:开心!  
  9. </br>  
  10. ${fromUserName}  
  11. </br>  
  12. ${time?date}  
  13.   
  14. </body>  
  15. </html>  

其中,${time?date}表示time是日期类型的变量,只取date部分。“?date”还可以使用“?datetime”或“?time”。

3、使用模板,测试用例:

 
  1. @Autowired  
  2. Configuration configuration; //freeMarker configuration  
  3.   
  4. @Test  
  5. public void sendHtmlMailUsingFreeMarker() throws Exception {  
  6.     Map<String, Object> model = new HashMap<String, Object>();  
  7.     model.put("time", new Date());  
  8.     model.put("message", "这是测试的内容。。。");  
  9.     model.put("toUserName", "张三");  
  10.     model.put("fromUserName", "老许");  
  11.       
  12.     Template t = configuration.getTemplate("welcome.ftl"); // freeMarker template  
  13.     String content = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);  
  14.   
  15.     logger.debug(content);  
  16.     //mailService.sendHtmlMail(to, "主题:html邮件", content);  
  17. }  


4、测试结果:

 

源代码参考:https://github.com/xujijun/my-spring-boot

FreeMarker官网:http://freemarker.org/

附:使用循环遍历一个List的模板:

 
  1. <html>  
  2. <body>  
  3.     <h3>发现错误!<href="${errorLogLink}" target="_blank">点击这里查看详情</a></h3>  
  4.       
  5.     <h3>错误列表:</h3>  
  6.       
  7.     <table border="1px solid #8968CD" style="border-collapse: collapse;"><tr><th>错误位置</th<th>数量</th<th>错误信息</th<th>错误类名</th<th>更多信息</th</tr>  
  8.     <#list errorList as error>  
  9.         <tr>  
  10.             <td>${error.pos}</td>  
  11.             <td>${error.count}</td>  
  12.             <td>${error.msg}</td>  
  13.             <td>${error.eName!}</td>  
  14.             <td>${error.details!}</td>  
  15.         </tr>  
  16.     </#list>  
  17.     </table>  
  18.       
  19. </body>  
  20. </html>  

注意:最后那个两个感叹号表示:如果error.eName/error.details的值为空,则用空格代替。感叹号后面也可以加一个缺省字符串,在空值的时候代替空值。如果不加感叹号会报错。

posted @ 2018-11-08 08:58  舞羊  阅读(185)  评论(0编辑  收藏  举报