開始使用
1.引入依賴
#SpringBoot預設提供了Thymeleaf的Starter,只需簡單引入依賴即可。
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-thymeleaf</artifactid> </dependency>
目前預設版本是2.1,如果想升級版本到3.0,可以這樣修改。
<properties> <thymeleaf.version>3.0.7.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version> </properties>
為了方便開發,專案案例採用了熱部署工具dev-tools ,這樣我們在修改頁面之後,IDEA會自動加載,從而達到實現熱更新的效果。
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-devtools</artifactid> <scope>runtime</scope> </dependency>
註:由於IDEA預設關閉了熱部署,需要做一些設定才能使其生效。解決方法:先按住Ctrl Shift Alt / 然後進入 Registry ,然後勾選compiler.automake.allow.when.app.running 即可。另外,Build->Compiler 也要勾選上Build Project automatically .
2. 新增相關配置
Thymeleaf預設開啟了頁面緩存,在開發的時候,應該要關閉快取。此外,通常我們也會指定頁面的存放路徑。 (預設是classpath:/templates/)
application.yml 配置如下: spring: thymeleaf: cache: false #关闭缓存 prefix: classpath:/views/ #添加路径前缀
3.寫HTML
寫Thymeleaf和書寫HTML5頁面沒有什麼不同,最大的轉變就是使用拓展屬性( th:xx)去跟服務端進行資料交互,保留原始頁面風格,也是Thymeleaf的推崇的風格。例如下面這個簡單的案例,啟動項目,我們發現頁面跳轉的是簡書的連接,這一點也驗證了Thymeleaf覆蓋原生頁面數據的極佳能力。
頁碼:
nbsp;html> <title>Thymeleaf</title> <h3 id="欢迎使用Thymeleaf">欢迎使用Thymeleaf!!</h3> <a>戳我有惊喜</a>
後端程式碼:
@Controller public class UserController { @GetMapping("/") public String index(Model model) { model.addAttribute("info", "user/list"); return "index"; } @GetMapping("/user") public String hehe(Model model) { model.addAttribute("user", new User(UUID.randomUUID().toString(), "yizhiwazi", "20170928")); return "user"; } @GetMapping("/user/list") public String userlist(Model model) { List<user> userList = new ArrayList(); userList.add(new User(UUID.randomUUID().toString(), "yizhiwazi", "20170928")); userList.add(new User(UUID.randomUUID().toString(), "kumamon", "123456")); userList.add(new User(UUID.randomUUID().toString(), "admin", "admin")); model.addAttribute("userList", userList); return "userList"; } }</user>
現在我們嘗試回填一個表單,展示單一使用者資訊。
<!-- 使用th:object 搭配*{} 可以省略对象名 -->
接下來,我們進入一個更複雜的案例,例如展示一個用戶列表信息,不需要編寫新的標籤,就可以完成對批量用戶的遍歷。
<h3 id="用户列表">用户列表</h3> <!--说明: th:each="obj,stat:${objects}" 分别代表单个实例,状态(可省略),待遍历对象--> <div> <input> 用户姓名:<input> 登录密码:<input> </div>
以上是SpringBoot+Thymeleaf基於HTML5現代模板引擎怎麼用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3漢化版
中文版,非常好用

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)