spring boot 使用FreeMarker模板

來源:互聯網
上載者:User

在spring boot中使用FreeMarker模板非常簡單方便,只需要簡單幾步就行:

1、引入依賴:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency>

2、建立模板:
<!DOCTYPE html><html><body><h4>親愛的${toUserName},你好。</h4><p style="color:blue;"> ${message}</p>祝:開心。</br>${fromUserName}</br>${time?date}</body></html>
其中,${time?date}表示time是日期類型的變數,只取date部分。“?date”還可以使用“?datetime”或“?time”。

3、使用模板,測試案例:
@AutowiredConfiguration configuration; //freeMarker configuration@Testpublic void sendHtmlMailUsingFreeMarker() throws Exception {Map<String, Object> model = new HashMap<String, Object>();model.put("time", new Date());model.put("message", "這是測試的內容。。。");model.put("toUserName", "張三");model.put("fromUserName", "老許");Template t = configuration.getTemplate("welcome.ftl"); // freeMarker templateString content = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);logger.debug(content);//mailService.sendHtmlMail(to, "主題:html郵件", content);}

4、測試結果:


原始碼參考:https://github.com/xujijun/my-spring-boot

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

附:使用迴圈遍曆一個List的模板:

<html><body><h3>發現錯誤。<a href="${errorLogLink}" target="_blank">點擊這裡查看詳情</a></h3>    <h3>錯誤清單:</h3>    <table border="1px solid #8968CD" style="border-collapse: collapse;"><tr><th>錯誤位置</th> <th>數量</th> <th>錯誤資訊</th> <th>錯誤類名</th> <th>更多資訊</th> </tr><#list errorList as error><tr><td>${error.pos}</td><td>${error.count}</td><td>${error.msg}</td><td>${error.eName!}</td><td>${error.details!}</td></tr></#list></table>    </body></html>
注意:最後那個兩個驚嘆號表示:如果error.eName/error.details的值為空白,則用空格代替。驚嘆號後面也可以加一個預設字串,在空值的時候代替空值。如果不加驚嘆號會報錯。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.