1. 概要

このクイックチュートリアルでは、ThymeleafにCSSクラスを条件付きで追加するいくつかの異なる方法を学習します。

Thymeleafに慣れていない場合は、その紹介を確認することをお勧めします。

2. th:ifを使用する

私たちの目標が生成することであると仮定しましょうそのクラスはサーバーによって決定されます。

<span class="base condition-true">
   I have two classes: "base" and either "condition-true" or "condition-false" depending on a server-side condition.
</span>

このHTMLが提供される前に、サーバーが条件を評価し、condition-trueクラスまたはcondition-falseクラス、および[ X191X]baseクラス。

HTMLをテンプレート化する場合、動的な動作のために条件付きロジックを追加する必要があるのは非常に一般的です。

まず、 th:if を使用して、最も単純な形式の条件付きロジックを示します。

<span th:if="${condition}" class="base condition-true">
   This HTML is duplicated. We probably want a better solution.
</span>
<span th:if="${!condition}" class="base condition-false">
   This HTML is duplicated. We probably want a better solution.
</span>

これにより、論理的に正しいCSSクラスがHTML要素にアタッチされることがわかりますが、コードのブロック全体を複製する必要があるため、このソリューションはDRY原則に違反します。

th:if を使用すると確かに役立つ場合もありますが、CSSクラスを動的に追加する別の方法を探す必要があります。

3. th:attrを使用する

Thymeleafは、 th:attrと呼ばれる他の属性を定義できる属性を提供します。

それを使って問題を解決しましょう:

<span th:attr="class=${condition ? 'base condition-true' : 'base condition-false'}">
   This HTML is consolidated, which is good, but the Thymeleaf attribute still has some redundancy in it.
</span>

baseクラスがまだ複製されていることに気付いたかもしれません。 また、クラスを定義するときに使用できるより具体的なThymeleaf属性があります。

4. th:classを使用する

th:class属性はth:attr =” class =…” のショートカットなので、代わりにbaseクラスを分離して使用しましょう。条件の結果:

<span th:class="'base '+${condition ? 'condition-true' : 'condition-false'}">
   The base CSS class still has to be appended with String concatenation. We can do a little bit better.
</span>

このソリューションは、私たちのニーズを満たし、DRYであるため、非常に優れています。 ただし、私たちが恩恵を受けることができるThymeleaf属性がまだもう1つあります。

5. th:classappendを使用する

基本クラスを条件付きロジックから完全に切り離すのは素晴らしいことではないでしょうか? 基本クラスを静的に定義し、条件付きロジックを関連する部分のみに減らすことができます:

<span class="base" th:classappend="${condition ? 'condition-true' : 'condition-false'}">
   This HTML is consolidated, and the conditional class is appended separately from the static base class.
</span>

6. 結論

Thymeleafコードを繰り返すたびに、後で役立つ可能性のある便利な条件付き手法について学びました。 最終的に、 th:classappendを使用すると、目標を達成しながら、DRYコードと関心の分離の最良の組み合わせが提供されることがわかりました。

これらの例はすべて、GitHub利用可能なThymeleafプロジェクトで見ることができます。