gerrytan
gerrytan

Reputation: 41143

How to check Thymeleaf fragment is defined

How do I check a Thymeleaf fragment is defined when using "template decoration instead of inclusion" technique?

In below example of template.html I only want the script tag to be rendered when the fragment is defined

<html th:fragment="page" xmlns:th="...">
  ...
  <div class="container" th:include="this :: content"></div>
  <script th:include="this :: script"></script>
  ...
</html>

But here in my index.html which uses the template above, no script fragment is defined but the script tag will still render anyway

<html th:include="template :: page">
  ...
  <div th:fragment="content">
    ...
  </div>
</html>

I've tried th:if="#{this :: script}" but no luck

Upvotes: 0

Views: 3939

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 149145

I played a little (...) with Thymeleaf, and here are my conclusions.

In the following, I will use tag for any given tag (div, script, span, etc.) and fragment an acceptable fragment syntax (this :: script, this :: content, template :: #menu, etc.)

When you use <tag th:include="fragment"/>,Thymeleaf allways generates a <tag>...</tag>. If it does not exist, the content is empty giving <tag></tag>. If the fragment exists, the content becomes the content of the fragment. For exemple using <div th:"other :: #foo/> for a fragment <p id="foo">bar</p> gives <div>bar</div>

When you use <tag th:replace="fragment"/>, Thymeleaf tries to replace it with the full fragment, tag included. with the following special cases :

  • if the fragment does not exist, Thymeleaf does not insert anything
  • if the fragment is identified by a th:fragment="id", Thymeleaf removes the th:fragment (ex: <p th:fragment="foo">bar</p> gives <p>bar</p>, whatever tag is).
  • if the fragment is identified by a dom element, Thymeleaf keeps the dom element (ex : <p id="foo">bar</p> gives <p id="foo">bar</p>, whatever tag is)

So, if you want to include the <script> fragment only if it exists, you simply have to identify it by <script th:fragment ...>...</script> when it exists and include it in your layout by :

<script th:replace="this :: script"/>

Upvotes: 2

Related Questions