Reputation: 4514
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>
Upvotes: 15
Views: 15443
Reputation: 444
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>
Upvotes: 0
Reputation: 1167
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.
Upvotes: 3
Reputation: 7095
Yout Thymeleaf fragment:
<div th:fragment="assets" th:remove="tag">
<script src="myscript"></script>
<script src="myscript2"></script>
</div>
Your code insert of the fragment:
<div th:replace="fragments/assets :: assets"></div>
This should render like:
<script src="myscript"></script>
<script src="myscript2"></script>
Upvotes: 1
Reputation: 161
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 :)
Upvotes: 16
Reputation: 1017
try the below
<div th:fragment="assets" th:remove="tag">
<script src="myscript"></script>
<script src="myscript2"></script>
</div>
Upvotes: 14
Reputation: 3557
The best way I've found to handle the script tag case is to use Thymeleaf Layouts since fragments are always nested inside a tag when using th:include or th:replace.
Further, one useful approach I use is to add the common scripts as normal at the bottom of a layout template and then add a final script content block e.g:
...
<script type="text/javascript" src="/resources/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="/resources/js/bootstrap.min.js"></script>
<div layout:fragment="script"></div>
</body>
</html>
Then pages which use the template can specify any extra javascript in a "script" block:
<script th:inline="javascript" layout:fragment="script" type="text/javascript">
/*<![CDATA[*/
// Some javascript...
/*]]>*/
Upvotes: 1