Thymeleaf変数
1. 序章
このチュートリアルでは、Thymeleafの変数を見ていきます。 Baeldungの記事のリストを取得し、ThymeleafHTMLテンプレートに表示するSpring Bootの例を作成します。
2. Mavenの依存関係
Thymeleafを使用するには、 spring-boot-starter-thymeleafおよびspring-boot-starter-webの依存関係を追加する必要があります。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3. Webコントローラー
まず、Baeldungの記事のリストを含むページを返すGETエンドポイントを使用してWebコントローラーを作成します。
@GetMapping で注釈が付けられたメソッドは、Modelという単一のパラメーターを取ります。 これは、Thymeleafテンプレート内でさらに使用できるすべてのグローバル変数を保持します。 この場合、モデルには1つのパラメーター(記事のリスト)しかありません。
Article クラスは、2つのStringフィールドnameとurlで構成されます。
public class Article {
private String name;
private String url;
// constructor, getters and setters
}
コントローラのメソッドの戻り値は、目的のThymeleafテンプレートの名前である必要があります。 この名前は、 src / resource /templateディレクトリにあるHTMLファイルに対応している必要があります。 この場合、 src / resource / template /articles-list.htmlになります。
Springコントローラーを簡単に見てみましょう。
@Controller
@RequestMapping("/api/articles")
public class ArticlesController {
@GetMapping
public String allArticles(Model model) {
model.addAttribute("articles", fetchArticles());
return "articles-list";
}
private List<Article> fetchArticles() {
return Arrays.asList(
new Article(
"Introduction to Using Thymeleaf in Spring",
"https://www.baeldung.com/thymeleaf-in-spring-mvc"
),
// a few other articles
);
}
}
アプリケーションを実行すると、記事ページが http:// localhost:8080 /articlesで利用できるようになります。
4. Thymeleafテンプレート
それでは、ThymeleafHTMLテンプレートに移りましょう。 追加のThymeleaf名前空間定義のみを含む標準のHTMLドキュメント構造である必要があります。
<html xmlns:th="http://www.thymeleaf.org">
これを以降の例のテンプレートとして使用します。ここでは、コンテンツのみを置き換えます。 鬼ごっこ:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf Variables</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<main>
...
</main>
</body>
</html>
5. 変数を定義する
Thymeleafテンプレートで変数を定義する方法は2つあります。 最初のオプションは、配列を反復処理するときに単一の要素を取得することです。
<div th:each="article : ${articles}">
<a th:text="${article.name}" th:href="${article.url}"></a>
</div>
その結果、
別の方法は、別の変数に基づいて新しい変数を定義することです。 たとえば、articles配列の最初の要素を取得できます。
<div th:with="firstArticle=${articles[0]}">
<a th:text="${firstArticle.name}" th:href="${firstArticle.url}"></a>
</div>
または、記事の名前だけを保持する新しい変数を作成できます。
<div th:each="article : ${articles}", th:with="articleName=${article.name}">
<a th:text="${articleName}" th:href="${article.url}"></a>
</div>
上記の例では、 ${article.name}および${articleName}フラグメントは置き換え可能です。
複数の変数を定義することも可能です。 たとえば、記事名とURLを保持する2つの別々の変数を作成できます。
<div th:each="article : ${articles}" th:with="articleName=${article.name}, articleUrl=${article.url}">
<a th:text="${articleName}" th:href="${articleUrl}"></a>
</div>
6. 変数スコープ
コントローラのModelに渡される変数には、グローバルスコープがあります。 これは、HTMLテンプレートのあらゆる場所で使用できることを意味します。
一方、HTMLテンプレートで定義された変数には、ローカルスコープがあります。 それらは、それらが定義された要素の範囲内でのみ使用できます。
たとえば、以下のコードは次のように正しいです要素は内にあります firstDiv :
<div id="firstDiv" th:with="firstArticle=${articles[0]}">
<a th:text="${firstArticle.name}" th:href="${firstArticle.url}"></a>
</div>
一方、firstArticleを別のdivで使用しようとすると、次のようになります。
<div id="firstDiv" th:with="firstArticle=${articles[0]}">
<a th:text="${firstArticle.name}" th:href="${firstArticle.url}"></a>
</div>
<div id="secondDiv">
<h2 th:text="${firstArticle.name}"></h2>
</div>
コンパイル時に、firstArticleがnullであるという例外が発生します。
org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'name' cannot be found on null
これは、
要素は、で定義された変数を使用しようとしています firstDiv、 これは範囲外です。
secondDiv内でfirstArticle変数を使用する必要がある場合は、 secondDiv で再度定義するか、これら2つのdivをラップする必要があります。 ]は共通要素にタグを付け、その中にfirstArticleを定義します。
7. 変数の値の変更
特定のスコープ内の変数の値を上書きすることもできます。
<div id="mainDiv" th:with="articles = ${ { articles[0], articles[1] } }">
<div th:each="article : ${articles}">
<a th:text="${article.name}" th:href="${article.url}"></a>
</div>
</div>
上記の例では、 articles 変数を再定義して、最初の要素が2つだけになるようにしました。
mainDiv、の外部では、articles変数の元の値が引き続きコントローラーに渡されることに注意してください。
8. 結論
このチュートリアルでは、Thymeleafで変数を定義して使用する方法を学びました。 いつものように、すべてのソースコードはGitHubで利用できます。