Spring Boot Thymeleaf でリンク(a href)を記載する方法

Thymeleaf でリンク(a href)を記載する方法をご紹介します。

Thymeleaf が便利な感じにレンダリングしてくれるので、それを認識するのに少し時間がかかりました。

4.4 リンクURL – Tutorial: Using Thymeleaf (ja)

Webサイトへのリンク

HTML では次のように書きたいとします。

<a href="http://localhost:8080/product/">Product Name</a>

Thymeleaf ではこのように書きます。

<a th:href="@{http://localhost:8080/product/}" th:text="${productName}">Product Name</a>

text をサーバー側から送られてきた値にしたい場合は、th:text を a要素 に含めて書きましょう。th:text が無い場合は普通に text が表示されます(上記だと Product List)。

リンク先URLにパラメータを付けたい場合、次のように書きます。

<a th:href="@{/product(orderId=${productName})}" th:text="${productName}">Product Name</a>

この場合、サーバー側が productName を abc とセットし、http://localhost:8080 がルートパスの場合、http://localhost:8080/product?orderId=abc に get でアクセスします。

画像へのリンク

HTML では次のように書きたいとします。

<link rel="icon" href="sample.png">
<a href="sample.png"></a>

Thymeleaf ではこのように書きます。

<link rel="icon" th:href="@{/sample.png}">
<a th:href="@{/sample.png}"></a>

画像ファイルは src/main/resources/static/sample.png となるよう配置します。

これは http://localhost:8080/product/ がルートパスの場合、href=”http://localhost:8080/product/sample.png” と記載したのと同じことです。もちろんWebブラウザで http://localhost:8080/product/sample.png にアクセスすると画像が表示されます。

file プロトコルでのリンク

レアなケースかもしれませんが http でなく fileプロトコル でリソースにアクセスしたい場合の対応です。

<div><a th:href="${'file://' + productPath}"></a></div>

‘file://’を付けないとhttp://が自動で付与されるので要注意です。

レンダリングされるとこのようになります。

<div><a href="file://serverName/productPath">//serverName/productPath</a></div>

このような書き方でも書けます。

<div><a th:href="@{file://__${productPath}__}" th:text="${productName}"></a></div>