S-JIS[2017-10-21] 変更履歴

Thymeleaf th:remove

Thymeleafのth:remove属性のメモ。


概要

th:remove属性は、タグを削除する属性。

th:remove属性を入れておくと、タグ自身を削除したり、タグのボディー部を削除したりすることが出来る。

ボディー部に同一のタグが複数ある場合(tableタグのボディー部のtrタグ等)、先頭のタグだけ残して残りを全て削除するといった事も出来る。
これは、テンプレートファイルを直接ブラウザーで表示する場合は全タグが見られるが、Thymeleafの動的な設定は先頭のタグにだけ行う、という場合が想定されている。
まさにThymeleafならではの属性だ(笑)

→条件に応じてタグを出力したり削除したりする場合はth:if属性を使う。
→複数のタグをまとめてコメントアウトしたい場合はThymeleafのパーサーレベルコメントを使う方法もある。


th:remove属性には以下の値を設定する.

設定値 説明
all タグ(ボディー部を含む)を削除する。
body ボディー部だけ削除する。
tag ボディー部だけ残す。
all-but-first 自分自身とボディー部の最初のタグだけ残し、残りのタグは削除する。
none 何もしない。

allの例

th:remove="all"(タグの削除)の例。

src/main/resources/templates/remove.html:

	<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>

all-but-firstの例

th:remove="all-but-first"(自分とボディー部の最初のタグだけ残す)の例。

src/main/resources/templates/remove.html:

	<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>

Thymeleafへ戻る / Spring Bootへ戻る / Spring Frameworkへ戻る / 技術メモへ戻る
メールの送信先:ひしだま