Keep Logic Minimal
Your templates should primarily handle presentation. Complex business logic belongs in your controllers or services, not in HTML templates. If you find yourself writing th:if chains that span dozens of lines, that's a smell.
<!-- Good: simple conditional -->
<p th:if="${user.premium}">Premium Member</p>
<!-- Bad: complex logic in template -->
<div th:if="${user.orders.size() > 5 && user.totalSpent > 1000 && !user.suspended}">
Loyal customer
</div>
Instead, compute that logic in your controller and pass a simple boolean like isLoyalCustomer. Templates should be dumb about data, smart about display.
Use Fragments for DRY Templates
Duplication in templates is just as bad as in code. If you're repeating HTML across pages, extract it into a fragment.
# fragments/header.html
<div th:fragment="header(title)">
<h1 th:text="${title}">Default Title</h1>
<nav>...</nav>
</div>
# pages/home.html
<div th:replace="~{fragments/header :: header('Home')}"></div>
Fragments keep your templates clean and maintainable. Change the header once, and every page that uses it updates automatically.
Try it Yourself →Avoid Scriptlets
You might be tempted to mix Java code directly into templates using scriptlets. Don't. It defeats the purpose of using a template engine and makes your code impossible to test.
<!-- Never do this -->
<%
List<String> items = (List<String>) request.getAttribute("items");
for (String item : items) {
%>
<p><%= item %></p>
<%
}
%>
<!-- Always do this -->
<p th:each="item : ${items}" th:text="${item}"></p>
Thymeleaf's natural templating is there for a reason. Embrace it and keep your templates clean of procedural code.
Organize Your Templates
A clear folder structure saves you headaches as your project grows. A common convention works well.
templates/
fragments/
header.html
footer.html
sidebar.html
pages/
home.html
about.html
blog/
list.html
detail.html
layout/
layout.html
layout-no-sidebar.html
Keep fragments separate from pages, and group related pages into subdirectories. It makes finding things intuitive for anyone who joins the project.
Naming Conventions
Consistent naming makes your templates predictable. Use lowercase with hyphens for file names, and meaningful names that describe the content.
<!-- Good names -->
user-profile.html
blog-post-list.html
dashboard-stats.html
<!-- Bad names -->
page1.html
temp.html
final-v2.html
Your future self will thank you. When you're debugging a template issue at 2 AM, a clear file name is worth its weight in gold.