I would like to choose the position of the children elements inside a fragment using Thymeleaf like in the following examples.
fragments.html:
<div th:fragment="awesomeFragment">
Some Text
<div><!-- children must be here --></div>
</div>
view.html:
<div th:replace="fragments :: awesomeFragment">
<a href="www.google.com"/>
</div>
Expected output:
<div>
Some Text
<div><a href="www.google.com"/></div>
</div>
Is it possible? If so, how could I do this?
You can do it via layouts.
Use Thymeleaf Layout Dialect for this.
(If you using Spring Boot
it's already turned on!)
The layout will be presented in this form :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<title></title>
</head>
<body>
<header>
Some text
</header>
<div layout:fragment="content">
<p>Page content goes here</p>
</div>
</body>
And you page will be:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="base/test">
<head>
<title></title>
</head>
<body>
<div layout:fragment="content">
<a href="www.test.com">Test.com</a>
</div>
</body>
I tried it in my Thymeleaf
test project. The source code of the page in browser turned out like you wanted :