8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Thymeleaf】コメントアウトっぽく見えたが違うやつ

Last updated at Posted at 2024-07-31

コメントアウト

消してはいけないコメントアウトがありました。
結論から言うと、コメントアウトっぽく見えますが、Thymeleafの記法ではコメントアウトではありませんでした。

これ

<!--/*/ <th:block th:include="fragments/navbars :: navbar"></th:block> /*/-->

何をしているか

コメントアウトの中身

Thymeleafのth:blockブロック

・通常のHTMLパーサーによっては無視される(=コメントアウトとして扱われる)。

・Thymeleafがこのテンプレートを処理する際には、このコメント内のThymeleafブロックを認識し、実行することができる。

コメントアウトされてる?

実はコメントアウトじゃなかった。

Thymeleafには、テンプレートが静的に(例えばプロトタイプとして)開かれた場合にはコメントになり、テンプレートとして実行された場合には通常のマークアップとして扱われる特別なコメントブロックもあります。

<span>hello!</span>
<!--/*/
  <div th:text="${...}">
    ...
  </div>
/*/-->
<span>goodbye!</span>

Thymeleafのパースシステムは単純にのマーカーを削除しますが、コンテンツは削除しないので、そのコンテンツがアンコメントされて残ります。ですので、テンプレートを実行するときにはThymeleafからは実際このように見えます:


<span>hello!</span>

  <div th:text="${...}">
    ...
  </div>

<span>goodbye!</span>

なんのために?

テンプレートエンジンの処理を制御しながら、HTMLとしてはコメントアウトされたままの状態を保つことができる。

確認 Thymeleafとは

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

テンプレートエンジンであるらしい。

Thymeleaf's main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.

HTMLをいい感じに表示させるためのものらしい。

With modules for Spring Framework, a host of integrations with your favourite tools, and the ability to plug in your own functionality, Thymeleaf is ideal for modern-day HTML5 JVM web development — although there is much more it can do.

Spring frameworkと相性が良いらしい。

結論

コメントアウトっぽく見えたが、コメントアウトではなく、
一つの書き方であった。

ブラウザはHTMLは読めるけど、Thymeleaf記法は読めない!

なので、テンプレートエンジンだけがこれを読めるようにこういう書き方をする必要があった!

テンプレートエンジンが読み込む(動的に読み込む)ときにのみ、通常のマークアップとして扱われ、以下のように処理されていた。
それによって、共通のnavbarをいい感じに読み込むことを達成。


<th:block th:include="fragments/navbars :: navbar"></th:block>

以上

8
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?