spring boot 使用FreeMarker模板

转自:http://blog.csdn.net/clementad/article/details/51942629

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

1、引入依赖:

[html]  view plain  copy
  1. <dependency>  
  2.     <groupId>org.springframework.boot</groupId>  
  3.     <artifactId>spring-boot-starter-freemarker</artifactId>  
  4. </dependency>  

2、创建模板:
[html]  view plain  copy
  1. <!DOCTYPE html>  
  2. <html>  
  3. <body>  
  4. <h4>亲爱的${toUserName},你好!</h4>  
  5.   
  6. <p 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、使用模板,测试用例:
[java]  view plain  copy
  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的模板:

[html]  view plain  copy
  1. <html>  
  2. <body>  
  3.     <h3>发现错误!<a 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的值为空,则用空格代替。感叹号后面也可以加一个缺省字符串,在空值的时候代替空值。如果不加感叹号会报错。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值