How to process Thymeleaf variable as HTML code?

January 04, 2020 No comments Thymeleaf th:utext HTML unescaped

1. Introduction

In this article, we will showcase how to process Thymeleaf variable as HTML code. Thymeleaf comes with special attribute th:utext, which is an alternative to th:text, used to present unescaped text on rendered templates.

2. th:utext attribute

Thymeleaf attribute th:utext can be used to present the evaluated variable in its original form without escaping special HTML characters. In the following example we show how to use it to present user comments that contains HTML tags:

<div id="commment-123456">
    <th:block th:utext="${comment.content}">comment</th:block"

Note that th:utext should be used with caution because it can cause security problems. Avoid unsecured user input in th:utext, content should be always checked and processed on the backend before presenting on the rendered website.

3. Conclusion

This article was dedicated to Thymeleaf th:utext attribute, that can be used to present variables without escaping their content.

{{ message }}

{{ 'Comments are closed.' | trans }}