Thymeleaf 的 th:attr 和 th:style 屬性的使用

一、th:attr

設置標籤屬性,多個屬性可以用逗號分隔

例:

1.後端接口:

@GetMapping(value = "/welcome")
public ModelAndView getWelcomeTitle() {
    ModelAndView modelAndView = new ModelAndView("welcome.html");
    modelAndView.addObject("attr1", "屬性值1");
    modelAndView.addObject("attr2", "屬性值2");
    return modelAndView;
  }

2.welcome.html:

只設置一個屬性的情況: <p th:attr="attr1=${attr1}"></p>
頁面實際解析爲:<p attr1="屬性值1"></p>
設置多個屬性的情況:<p th:attr="attr1=${attr1}, attr2=${attr2} "></p>
頁面實際解析爲:<p attr1="屬性值1" attr2="屬性值2"></p>

二、th:style

設置標籤樣式,多個樣式需要拼接

1.後端接口:

@GetMapping(value = "/welcome")
public ModelAndView getWelcomeTitle() {
    ModelAndView modelAndView = new ModelAndView("welcome.html");
    modelAndView.addObject("font-size", "100px");
    modelAndView.addObject("font-weight", "700");
    modelAndView.addObject("font-family", "courier");
    return modelAndView;
  }

2.welcome.html:

只設置一個屬性的情況: <p th:style="'font-size:' + ${font-size}"></p>
頁面實際解析爲: <p th:style="font-size:100px"></p>
設置多個屬性的情況: <p th:style="'font-size:' + ${font-size} + '; font-weight:' + ${font-weight}"></p>
頁面實際解析爲: <p th:style="font-size:100px; font-weight:700"></p>
也可以像這樣追加一個:<p th:style="'font-size:' + ${font-size} + ';' + " th:styleappend ="'font-weight:' + ${font-weight}" ></p>
頁面實際解析爲:<p th:style="font-size:100px; font-weight:700"></p>
也可以像這樣追加多個:<p th:style="'font-size:' + ${font-size} + ';'" th:styleappend ="'font-weight:' + ${font-weight} + '; font-family:' + ${font-family}" ></p>
頁面實際解析爲:<p th:style="font-size:100px; font-weight:700; font-family:courier"></p>

三、參考文檔

https://o7planning.org/en/12373/thymeleaf-th-class-th-classappend-th-style-th-styleappend

四、吐槽

後端剛接觸 Thymeleaf 不久,今天有個需求是爲標籤添加多個樣式,查了很久才解決。這該死的 th:attr 和 th:style 添加多個屬性/樣式的方式不一樣,真坑!

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