Skip to content
BeginnerBackend Notes

Thymeleaf for Spring Boot: From th:text to Fragments

A practical path through Thymeleaf — basic attribute binding, object selection, and the fragment pattern that kills copy-pasted navbars.

Hen HeangJune 10, 20265 min read
Spring BootJavaThymeleaf

Thymeleaf is Spring Boot's default server-side template engine — the natural successor to JSP, and tightly integrated with the rest of the framework. Three layers cover almost everything I use it for.

Layer 1 — basic syntax

html
<p th:text="${user.name}">Default Name</p>
<input type="text" th:value="${user.email}" />

<tr th:each="note : ${notes}">
    <td th:text="${note.title}">Title</td>
</tr>

<div th:if="${user.isAdmin}">Admin Panel</div>

Layer 2 — patterns from real projects

th:object plus the *{} shorthand binds a form to a specific object without repeating its name on every field:

html
<form th:object="${member}">
    <input type="text" th:field="*{name}" />
</form>

<a th:href="@{/notes/view(id=${note.id})}">View Note</a>

<span th:text="|Welcome, ${user.name}!|"></span>

Layer 3 — fragments kill copy-pasted navbars

html
<!-- footer.html -->
<footer th:fragment="copy"> &copy; 2026 dev-notes </footer>

<!-- main.html -->
<div th:replace="~{footer :: copy}"></div>

Combined with the Layout Dialect for a decorator-style shared page shell, and sec:authorize for role-based visibility, fragments are what turn a handful of near-identical pages into one navbar defined once.

Tip

Need a Java value inside inline JavaScript? [[${user.id}]] inlining is safer than string-building a <script> tag by hand.