Thymeleaf - Include content of fragment

Viewed 14242

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

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.

If you like to pass some parameters to the script, you can to like this (Google reCaptchaV3 example):

in your HTML, do this:

<th:block th:include="fragments/script-google-recaptcha-submit.html :: on-submit(form = 'contact-form')"></th:block>

in your 'script-HTML', do this:

<th:block th:fragment="on-submit">
    <script th:inline="javascript">
        /*<![CDATA[*/

        function onSubmit(token) {
            console.log(/*[[${form}]]*/);
            document.getElementById(/*[[${form}]]*/).submit();
        }

        /*]]>*/
    </script>
</th:block>
Related