Thymeleafでハイパーリンクを実装する

はじめに

こんにちは、新卒2年目の岡崎です。今回は、Thymeleafでハイパーリンクを実装する方法を紹介します。

環境

  • Thymeleaf 3.3.0

前提

以下のようなオブジェクトが存在することを仮定します。

@Data
public class Test {
    private Long id;
    
    private String name;
    
    // 以下略
}

オブジェクトのリストを表示する場合、以下のコントローラーを使います。

    @GetMapping("list/test")
    public String getTestList(
            Model model
    ) {
            final List<Test> testList = testUseCase.getTestList();

            model.addAttribute("testList", testList);

            return "test/list/index";
    }

また、オブジェクトを取得する場合は、idから表示します。

    @GetMapping("test")
    public String getTest(
            @ModelAttribute Model model,
            TestRequestDto request,
    ) {
            final Test test = testUseCase.getTestById(request.id(), request.type());

            model.addAttribute("test", test);

            return "test/index";
    }
public record TestRequestDto(
        @NotNull @Positive
        Long id,

        @Nullable 
        String type
) {
}

test/list/index.htmlを用意します。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <title>Test List</title>
    <meta charset="utf-8"/>
</head>

<body>

</body>
</html>

test/index.htmlを用意します。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <title>Test</title>
    <meta charset="utf-8"/>
</head>

<body>
   <div>sample</div>
</body>
</html>

実装

前提で紹介したリストの表示を行います。

test/list/index.htmlを変更します。

<body>

   <th:block th:each="test : ${testList}">
       <tr>
           <td th:text="${test.getId()}"></td>
           <td th:text="${test.getName()}"></td>
                // 以下略
       </tr>
   </th:block>

</body>
</html>

idをタップすると、詳細画面を見ることができるようにするため、ハイパーリンクを作成します。

<th:block th:each="test : ${testList}">
    <tr>
        <td>
          <a th:href="@{/test(id=${test.getId()})}" th:text="${test.getId()}"></a>
        </td>
        <td th:text="${test.getName()}"></td>
                // 以下略
    </tr>
</th:block>

th:href=@url(パラメーター名=${変数名})と書くことで、変数の値をクエリーパラメーターとして指定することができます。

ハイパーリンクに、パスのクエリーパラメーターを使う方法

実際のケースで、ハイパーリンクに、パスのクエリーパラメーターを使いたい場合がありました。この時の実装例を紹介します。

下記のようなパスが存在していると仮定します。

http://localhost8080/test/list?type=TEST

<div th:with="type=${param.type}">
  <a th:href="@{/test(id=${test.getId(), type=${type})}" th:text="${test.getId()}"></a>
</div>

この場合、<div th:with="クエリーパラメーター=${param.クエリーパラメーター}"> 〜 </div> と実装すれば、そのdivタグの中でクエリーパラメーターを使うことができます。

最後に

今回は、Thymeleafでハイパーリンクを実装する方法について紹介しました。

最後に、エキサイトではデザイナー、フロントエンジニア、バックエンドエンジニア、アプリエンジニアを絶賛募集しております!

興味があればぜひぜひ連絡ください!

www.wantedly.com