Adrian Ber
Adrian Ber

Reputation: 21390

Part of Thymeleaf fragment included only once

I have a Thymeleaf fragment like this

<div th:fragment="f1">
    <script src="x.js"></script>
    <div> ... </div>
</div>

The script part I want to include it only once, even though I will include f1 more than once in the page. What's the easiest/cleanest way to achieve this?

I can even split this fragment into two fragments and then the problem will be reduced on how to include a fragment only once in a page.

It can be somehow done if we'll be able to manipulate the request attributes from Thymeleaf. I understand that Thymeleaf if for rendering only, but a feature like this could be useful. Even to have something like include-once or if the included fragment has an id(or th:id) attribute, to include it only once.

Upvotes: 2

Views: 666

Answers (1)

user3404622
user3404622

Reputation: 101

use #ids.

<div th:fragment="f1">
  <script src="x.js" th:if="${#ids.seq('f1.script.') == 'f1.script.1'}"></script>
  hello
</div>

or

<div th:fragment="f1">
  <script src="x.js" th:if="${#ids.next('f1.script.') == 'f1.script.1'}" th:id="${#ids.seq('f1.script.')}"></script>
  hello
</div>

Upvotes: 6

Related Questions