Keywords: Thymeleaf | templates | dynamic text | HTML structure
Abstract: This article addresses the issue in Thymeleaf templates where th:text removes inner HTML structures. By using th:inline='text' or th:remove='tag', dynamic text can be inserted without removing child elements, providing a solution for common templating challenges. It explains the cause, offers code examples, and compares different approaches for optimal use cases.
Problem Description
In Thymeleaf template development, developers often encounter issues where the th:text attribute removes all inner HTML structures, resulting in only dynamic text output while ignoring child elements. For example, the following code:
<h1 th:text="${header.title}"> title <small th:text="${header.subtitle}">Subtitle</small> </h1>Expects output as <h1> TITLE <small> SUBTITLE</small> </h1>, but the actual output is <h1> TITLE </h1>, because th:text replaces the entire element content.
Solution
To solve this problem, Thymeleaf provides the th:inline='text' attribute. By setting this attribute on the parent element, dynamic text can be embedded using the [[...]] syntax while preserving child elements.
<h1 th:inline="text"> [[${header.title}]] <small th:text="${header.subtitle}">Subtitle</small> </h1>This ensures correct output with both title and subtitle.
Alternative Approach
Another method is to use the th:remove="tag" attribute. By setting dynamic text on a temporary element and removing its tag, other elements remain unaffected.
<h1> <span th:text="${header.title}" th:remove="tag">title</span> <small th:text="${header.subtitle}">Subtitle</small> </h1>This approach is more flexible but may increase template complexity.
Summary
In Thymeleaf, when inserting dynamic text while preserving HTML structures, it is recommended to use the th:inline='text' attribute. It is concise and efficient, suitable for most scenarios. Developers should choose the appropriate method based on specific needs to enhance template maintainability and rendering quality.