mcpField
T
thymeleaf

thymeleaf

github.com/claude-dev-suiteDevelopment4694 installsUpdated 2d ago
Repository

About thymeleaf

thymeleaf is a quick-reference skill for developers working with Thymeleaf templates. It covers syntax, form binding, reusable layouts, safe output, and troubleshooting.

Key features

  1. 01Variables, loops, and conditionals
  2. 02Reusable fragments and layouts
  3. 03Form binding and JavaScript inlining
  4. 04Expression and utility-object reference
  5. 05Safe-output practices and troubleshooting

Use cases

  1. 01Building Spring page templates
  2. 02Binding form data and showing errors
  3. 03Extracting reusable page fragments
  4. 04Diagnosing variable or template-loading issues

Install

Copy the command and run it in a terminal.

$npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill thymeleaf

After installing, type/thymeleafin Claude Code to confirm it loaded.

Details

From the project README

Thymeleaf - Quick Reference

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: thymeleaf for comprehensive documentation.

Pattern Essenziali

Basic Syntax
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title th:text="${title}">Default</title>
</head>
<body>
    <h1 th:text="${message}">Hello</h1>
    <p th:text="'Welcome, ' + ${name}">Welcome, User</p>
</body>
</html>
Variables & Loops
<!-- Variable -->
<p th:text="${user.name}">Name</p>

<!-- Loop -->
<tr th:each="user : ${users}">
    <td th:text="${user.name}">Name</td>
    <td th:text="${user.email}">Email</td>
</tr>

<!-- Conditionals -->
<p th:if="${user.active}">Active</p>
<p th:unless="${user.active}">Inactive</p>
Email Service
@Service
@RequiredArgsConstructor
public class EmailService {

    private final TemplateEngine templateEngine;
    private final JavaMailSender mailSender;

    public void sendWelcome(User user) {
        Context ctx = new Context();
        ctx.setVariable("userName", user.getName());
        ctx.setVariable("actionUrl", "https://app.com/verify");

        String html = templateEngine.process("emails/welcome", ctx);

        MimeMessage msg = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg, true);
        helper.setTo(user.getEmail());
        helper.setSubject("Welcome!");
        helper.setText(html, true);
        mailSender.send(msg);
    }
}
Fragments & Layouts
<!-- fragments/common.html -->
<nav th:fragment="navigation">
    <ul>
        <li><a th:href="@{/}">Home</a></li>
        <li><a th:href="@{/about}">About</a></li>
    </ul>
</nav>

<footer th:fragment="footer(year)">
    <p th:text="'© ' + ${year} + ' My Company'">© 2024 My Company</p>
</footer>
<!-- Usage: th:replace vs th:insert -->
<!-- th:replace - replaces host tag completely -->
<div th:replace="~{fragments/common :: navigation}"></div>

<!-- th:insert - inserts fragment inside host tag -->
<div th:insert="~{fragments/common :: navigation}"></div>

<!-- With parameters -->
<div th:replace="~{fragments/common :: footer(${#dates.year(#dates.createNow())})}"></div>
Layout Dialect
<!-- pom.xml -->
<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
<!-- layouts/main.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <title layout:title-pattern="$CONTENT_TITLE - $LAYOUT_TITLE">My App</title>
    <link rel="stylesheet" th:href="@{/css/main.css}"/>
</head>
<body>
    <header th:replace="~{fragments/common :: navigation}"></header>

    <main layout:fragment="content">
        <!-- Page content goes here -->
    </main>

    <footer th:replace="~{fragments/common :: footer}"></footer>

    <script layout:fragment="scripts"></script>
</body>
</html>
<!-- pages/home.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layouts/main}">
<head>
    <title>Home</title>
</head>
<body>
    <main layout:fragment="content">
        <h1>Welcome!</h1>
        <p th:text="${message}">Content</p>
    </main>

    <th:block layout:fragment="scripts">
        <script th:src="@{/js/home.js}"></script>
    </th:block>
</body>
</html>
Form Binding
<form th:action="@{/users}" th:object="${userForm}" method="post">
    <div>
        <label for="name">Name:</label>
        <input type="text" id="name" th:field="*{name}"
               th:classappend="${#fields.hasErrors('name')} ? 'error' : ''"/>
        <span th:if="${#fields.hasErrors('name')}"
              th:errors="*{name}" class="error-msg">Name error</span>
    </div>

    <div>
        <label for="email">Email:</label>
        <input type="email" id="email" th:field="*{email}"/>
        <span th:if="${#fields.hasErrors('email')}"
              th:errors="*{email}" class="error-msg">Email error</span>
    </div>

    <div>
        <label for="role">Role:</label>
        <select id="role" th:field="*{role}">
            <option value="">-- Select --</option>
            <option th:each="role : ${roles}"
                    th:value="${role}"
                    th:text="${role.displayName}">Role</option>
        </select>
    </div>

    <button type="submit">Save</button>
</form>
JavaScript Inlining
<script th:inline="javascript">
    // Natural templates with fallback
    const user = /*[[${user}]]*/ { name: 'default' };
    const userId = /*[[${user.id}]]*/ 0;
    const isAdmin = /*[[${user.admin}]]*/ false;

    // Array
    const items = /*[[${items}]]*/ [];

    // Conditional in JS
    /*[# th:if="${user != null}"]*/
    console.log('User:', user.name);
    /*[/]*/
</script>

<!-- CSS inlining -->
<style th:inline="css">
    .user-bg {
        background-color: [[${user.favoriteColor}]];
    }
</style>
Utility Objects
<!-- Dates -->
<p th:text="${#dates.format(user.createdAt, 'dd/MM/yyyy HH:mm')}">Date</p>
<p th:text="${#dates.dayOfWeekName(date)}">Monday</p>

<!-- Strings -->
<p th:text="${#strings.toUpperCase(name)}">NAME</p>
<p th:text="${#strings.abbreviate(text, 100)}">Truncated...</p>
<p th:text="${#strings.isEmpty(value) ? 'N/A' : value}">Value</p>
<p th:text="${#strings.listJoin(items, ', ')}">a, b, c</p>

<!-- Numbers -->
<p th:text="${#numbers.formatDecimal(price, 1, 2)}">10.50</p>
<p th:text="${#numbers.formatCurrency(amount)}">$1,234.56</p>

<!-- Lists -->
<p th:text="${#lists.size(users)}">Count</p>
<p th:if="${#lists.isEmpty(users)}">No users</p>
<p th:text="${#lists.contains(roles, 'ADMIN')}">Has admin</p>

<!-- Aggregates -->
<p th:text="${#aggregates.sum(prices)}">Total</p>
<p th:text="${#aggregates.avg(scores)}">Average</p>
Switch/Case
<div th:switch="${user.role}">
    <p th:case="'ADMIN'">Administrator</p>
    <p th:case="'MANAGER'">Manager</p>
    <p th:case="'USER'">Regular User</p>
    <p th:case="*">Unknown Role</p>
</div>
Iteration Status
<tr th:each="user, stat : ${users}"
    th:class="${stat.odd} ? 'odd' : 'even'">
    <td th:text="${stat.index}">0</td>
    <td th:text="${stat.count}">1</td>
    <td th:text="${user.name}">Name</td>
    <td th:if="${stat.first}">First!</td>
    <td th:if="${stat.last}">Last!</td>
</tr>

Expressions

ExprUso
${var}Variable
*{prop}Selection (con th:object)
@{/url}Link URL
#{msg}Message i18n
~{frag}Fragment

Best Practices

DoDon't
Use th:text for escaped outputUse th:utext with user input (XSS)
Use fragments for reusable componentsDuplicate HTML across templates
Keep templates simplePut complex logic in templates
Use i18n messagesHardcode text strings
Use layout dialectsRepeat layout in every page

When NOT to Use This Skill

  • REST APIs - Use spring-rest skill for JSON responses
  • SPA frontends - Use React, Vue, or Angular
  • PDF reports - Use JasperReports or iText
  • High-traffic APIs - Consider static frontends

Anti-Patterns

Anti-PatternProblemSolution
th:utext with user inputXSS vulnerabilityUse th:text for escaping
Complex logic in templatesHard to test, maintainMove logic to controller
Missing th namespaceSilent failuresAlways declare xmlns:th
Inline styles everywhereInconsistent UIUse CSS classes
No fragment reuseCode duplicationExtract common fragments

Quick Troubleshooting

ProblemDiagnosticFix
Variables not renderingCheck th: prefixUse th:text, th:value
Template not foundCheck pathPlace in templates/ folder
Iteration not workingCheck th:each syntaxVerify collection is passed
Fragments not includedCheck path syntaxUse ~{fragments/name :: fragment}
i18n not workingCheck messages.propertiesVerify file location and keys

Reference Documentation

Comments

Markdown supported