Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf - Include content of fragment

Thymeleaf fragment:

<div th:fragment="assets">
    <script src="myscript"></script>
    <script src="myscript2"></script>
</div>

This piece of code inserts the fragment:

<div th:replace="fragments/assets :: assets"></div>


How to include only content without the wrapper?

<script src="myscript"></script>
<script src="myscript2"></script>
like image 434
kidwon Avatar asked Mar 14 '16 12:03

kidwon


People also ask

How do I add if condition in Thymeleaf?

In some situations, you want a certain snippet of the Thymeleaf Template to appear in the result if a certain condition is evaluated as true. To do this you can use the attribute th:if. Note: In Thymeleaf, A variable or an expression is evaluated as false if its value is null, false, 0, "false", "off", "no".

Is Thymeleaf better than JSP?

Thymeleaf is way better in my opinion because it have good underlying priciples and exploits natural behaviour of browsers. Jsp makes html hard to read, it becomes weird mixture of html and java code which makes a lot of problems in comunication between designer - developer.


3 Answers

try the below

<div th:fragment="assets" th:remove="tag">
    <script src="myscript"></script>
    <script src="myscript2"></script>
</div>
like image 98
Balaji Krishnan Avatar answered Oct 23 '22 12:10

Balaji Krishnan


You can use th:block to include only content of a block.

Define your fragment like -

<th:block th:fragment="assets">
    <script src="myscript"></script>
    <script src="myscript2"></script>
</th:block>

And include like this -

<th:block th:include="fragments/assets :: assets"></th:block>

Hope this will help you :)

like image 15
Dhanendra Kumar Avatar answered Oct 23 '22 11:10

Dhanendra Kumar


Use this:

<div id="testId" th:include="fragments/assets :: assets"></div>

It will also insert the specified fragment as the body of its with in outer tag but excluding the fragment tag.

like image 3
Sachin Kumar Avatar answered Oct 23 '22 10:10

Sachin Kumar