springboot bootstrap和thymeleaf的使用


最近想用springboot自己用業余時間寫一個網站,發現坑很多,遇到很多問題,包括前端和后端,前端的基礎太不扎實了,還有很多內容需要進一步學習。

這里轉一篇bootstrap和thymeleaf在springboot的使用

Spring Boot項目的默認模板引擎是Thymeleaf,這沒什么好說的,個人覺得也非常好,因為這款引擎可以前后端同時開發,類似th:xxx這樣的內聯標簽屬性會被html5無情忽視,所以前台在開發靜態頁面的時候就正常開發,正常預覽,后台拿來開發好的模板加上這個標簽分分鍾就開始用,這也是這個引擎的最大好處(你把后台jsp頁面在瀏覽器直接打開就知道這是什么意思了)。
bootstrap作為老牌前台框架,有大量開發好的優秀模板(尤其是各種admin模板),拿來就能用。但是最近在試圖把網上下載的一套開源bootstrap模板整合到thymeleaf時遇到一些小問題,經過查閱資料最后解決了,記錄一下。

這個問題就是,當你把前台模板直接copy到工程中(css/js/img等直接放在resources/static文件夾下,頁面放在resources/templates下),類似這樣:

 
Paste_Image.png

login.html中加一句話變成thymeleaf模板

<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> ... 

這時你直接訪問這個login.html會報錯。
查閱官方文檔得知原因:springboot默認使用 Thymeleaf 2.1版本,這個版本無法識別html5中常見的自閉合標簽,如<input type="text" />。好弱的感覺。
解決辦法時強制更換到Thymeleaf 3:在pom.xml中添加屬性:

<properties> <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version> </properties> 

然后在application.properties中添加以下一句:
spring.thymeleaf.mode: HTML
注意這一句是必須要加的,需要顯式指定。
以下是官方原話:

By default, spring-boot-starter-thymeleaf
uses Thymeleaf 2.1. If you are using the spring-boot-starter-parent
, you can use Thymeleaf 3 by overriding thethymeleaf.version
and thymeleaf-layout-dialect.version
properties, for example:

<properties> <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version> </properties> 

To avoid a warning message about the HTML 5 template mode being deprecated and the HTML template mode being used instead, you may also want to explicitly configure spring.thymeleaf.mode to be HTML, for example:
spring.thymeleaf.mode: HTML

然后就可以歡快的開擼代碼了。



作者:Angeladaddy
鏈接:https://www.jianshu.com/p/a80d2ff15b47
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM