Thymeleaf制御文
Thymeleaf(タイムリーフ)でよく使いそうな制御文などを備忘録として残します。
Spring Boot 1.5.7で取得したら、Thymeleaf 2.1.5で落ちてきたため、このバージョンの備忘録となります。
適宜追加していく予定です。
本家のドキュメントはこちら
Spring Boot 1.5.7で取得したら、Thymeleaf 2.1.5で落ちてきたため、このバージョンの備忘録となります。
適宜追加していく予定です。
[広告]
[広告]
本家のドキュメントはこちら
利用するデータ
insert into product(name, price) values ('商品A', 100); insert into product(name, price) values ('商品B', 200); insert into product(name, price) values ('商品C', 300); insert into product(name, price) values ('商品D', 400); insert into product(name, price) values ('商品E', 500);
オブジェクトを表示
・コントローラmv.addObject("product", productRepo.findAll()[0])・index.html
<span th:text="${product.name}"></span> ⇒商品A
メッセージを表示
・resources/messages.propertieshello.wolrd=こんにちわ、世界・resources/application.properties
spring.messages.basename=messages spring.messages.cache-seconds=-1 spring.messages.encoding=UTF-8
<span th:text="#{hello.wolrd}"></span>
アスタリスク構文
オブジェクト名を省略してかけるため、フィールドが多いと便利にかけそう。 ・index.html<div th:object="${product}"> <!-- タグ内は「product.」を省略してアスタリスク変数として利用可能 --> <span th:text="*{name}"></span> <span th:text="*{price}"></span> </div>
if文
・コントローラmv.addObject("productList", productRepo.findAll())・index.html
><div th:each="product : ${productList}"> <div th:if="${product.name == '商品A'}"> <span th:text="${product.name}"></span> <span th:text="${product.price}"></span> </div> </div> ⇒商品A 100・index.html
><div th:each="product : ${productList}"> <div th:if="${product.name != '商品A'}"> <span th:text="${product.name}"></span> <span th:text="${product.price}"></span> </div> </div> ⇒商品A 100 ⇒商品B 200 ⇒商品C 300 ⇒商品D 400・index.html
<div th:each="product : ${productList}"> <!-- 400未満 --> <div th:if="${product.price lt 400}"> <span th:text="${product.name}"></span> <span th:text="${product.price}"></span> </div> </div> ⇒商品A 100 ⇒商品B 200 ⇒商品C 300・index.html
<div th:each="product : ${productList}"> <!-- 200超過、400未満 --> <div th:if="${product.price gt 200 and product.price lt 400}"> <span th:text="${product.name}"></span> <span th:text="${product.price}"></span> </div> </div> ⇒商品C 300・演算子の説明
lt | 「<」の意味 |
gt | 「>」の意味 |
le | 「>=」の意味 |
ge | 「<=」の意味 |
and | 「&&」の意味 |
or | 「||」の意味 |
?: | エルビス演算子。groovyでなくても使えるみたい |
コメントを残す