Thymeleafのth:remove属性のメモ。
th:remove属性は、タグを削除する属性。
th:remove属性を入れておくと、タグ自身を削除したり、タグのボディー部を削除したりすることが出来る。
ボディー部に同一のタグが複数ある場合(tableタグのボディー部のtrタグ等)、先頭のタグだけ残して残りを全て削除するといった事も出来る。
これは、テンプレートファイルを直接ブラウザーで表示する場合は全タグが見られるが、Thymeleafの動的な設定は先頭のタグにだけ行う、という場合が想定されている。
まさにThymeleafならではの属性だ(笑)
→条件に応じてタグを出力したり削除したりする場合はth:if属性を使う。
→複数のタグをまとめてコメントアウトしたい場合はThymeleafのパーサーレベルコメントを使う方法もある。
th:remove属性には以下の値を設定する.
設定値 | 説明 |
---|---|
all |
タグ(ボディー部を含む)を削除する。 |
body |
ボディー部だけ削除する。 |
tag |
ボディー部だけ残す。 |
all-but-first |
自分自身とボディー部の最初のタグだけ残し、残りのタグは削除する。 |
none |
何もしない。 |
th:remove="all"
(タグの削除)の例。
<h1>all</h1> <table border="1"> <tr> <td>aaa</td> <td>111</td> </tr> <tr th:remove="all"> <td>bbb</td> <td>222</td> </tr> <tr th:remove="all"> <td>ccc</td> <td>333</td> </tr> </table>
↓生成されるHTML
<h1>all</h1> <table border="1"> <tr> <td>aaa</td> <td>111</td> </tr> </table>
th:remove="all-but-first"
(自分とボディー部の最初のタグだけ残す)の例。
<h1>all-but-first</h1> <table border="1" th:remove="all-but-first"> <tr> <td>aaa</td> <td>111</td> </tr> <tr> <td>bbb</td> <td>222</td> </tr> <tr> <td>ccc</td> <td>333</td> </tr> </table>
↓生成されるHTML
<h1>all-but-first</h1> <table border="1"> <tr> <td>aaa</td> <td>111</td> </tr> </table>