我踩的thymeleaf渲染框架的坑

最近公司用的thymeleaf來做前段渲染框架,老實說我比較喜歡它對html代碼的0入侵,但是正因爲這一點我又覺得好坑,無法像freemarker那樣隨便輸出動態數據,所有的東西都得和標籤有些關聯才行。

1. thymeleaf渲染元素屬性值的坑

公司有個業務上我需要對a標籤的href屬性加一個動態id參數上去,

<a href="asda?id={user.id}">click</a>

這裏我準備吧{user.id}替換爲動態的值,但是,thymeleaf坑來了,它是不允許你這樣乾的,這樣幹最後得出的結果就是值渲染不上去,然後我又試了好幾種辦法,比如加上[[${user.id}]]上去,失敗·····

最後,天無絕人之路,有了解決辦法
使用th:attr標籤來做

th:attr="href=asda?id=${user.id}"

然而,渲染的時候竟然給我報錯了。。。。讓我感覺應該是字符串拼接的問題。最後加了個單引號,終於解決問題。。。哭暈在地…..

th:attr="href='asda?id='+${user.id}"

最後完整的格式:

<a th:attr="href='asda?id='+${user.id}">click</a>

2017年3月23日更新
其實還可以這樣去做,如下

<a th:href="'asda?id='+${user.id}">click</a>

2. thymeleaf3做layout佈局的坑

要做layout佈局,首先得給TemplateEngine添加一個layout Dialect才行,然而我一開始並不知道,配置方法:

 public TemplateEngine templateEngine() {
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setTemplateResolver(templateResolver());
    engine.setEnableSpringELCompiler(true);
    engine.addDialect(new LayoutDialect());
    return engine;
  }

如果不設置EnableSpringElCompiler爲true,項目run的時候會失敗並報錯。。找了半天。配置好後,其他的問題都已經不是問題,需要注意的是,使用layout佈局需要對子頁面進行的html標籤添加一個layout屬性,例如:

<html lang="en" layout:decorator="mobile/layout">

3.Spring Boot 配置thymeleaf3.

由於默認的spring-boot-starter-thymeleaf 使用Thymeleaf2.1,我們要使用thymeleaf3去替換thymeleaf和thymeleaf-layout-dialect版本號,例如

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

詳細的配置請查看Spring Boot 官方的thymeleaf3的demo演示
如果你使用了其他的自動配置Thymeleaf,應該去複寫他們的版本號。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章