将 Thymeleaf 变量处理为 HTML 代码而不是文本

我使用 Thymeleaf 来处理 HTML 模板,我知道如何从控制器中附加内联字符串,但是现在我想在页面中附加一段 HTML 代码。

例如,让我们停留在我的 Java 应用程序中:

String n="<span><i class=\"icon-leaf\"></i>"+str+"</span> <a href=\"\"></a>\n";


final WebContext ctx = new WebContext(request, response,
servletContext, request.getLocale());
ctx.setVariable("n", n);

我需要在 HTML 页面中写些什么,以便它将被 n变量的值替换,并作为 HTML 代码处理,而不是将其编码为文本?

70951 次浏览

You can use th:utext attribute that stands for unescaped text (see documentation). Use this with caution and avoid user input in th:utext as it can cause security problems.

<div th:remove="tag" th:utext="${n}"></div>

If you want short-hand syntax you can use following:

[(${variable})]

Escaped short-hand syntax is

[[${variable}]]

but if you change inner square brackets [ with regular ( ones HTML is not escaped.

Example within tags:

<div>
[(${variable})]
</div>