处理thymeleaf变量作为html代码而不是文本

Ale*_*rin 52 java thymeleaf

我正在使用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);
Run Code Online (Sandbox Code Playgroud)

我需要在html页面中编写什么内容,以便将其替换为"n"变量并作为html代码处理而不是将其编码为文本?

mic*_*man 87

您可以使用th:utext代表未转义文本的属性(请参阅文档).请谨慎使用,避免用户输入,th:utext因为它可能会导致安全问题.

<div th:remove="tag" th:utext="${n}"></div>
Run Code Online (Sandbox Code Playgroud)

  • 需要注意的重要事项:使用 utext 会使您容易受到跨站点脚本攻击。攻击者可以将恶意 html 存储在您的 `n` 变量中,每次在用户浏览器上呈现页面时都会执行该变量。见 https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet (3认同)
  • 更新了v3的链接http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#unescaped-text (2认同)

mic*_*czy 19

如果您想要简写语法,可以使用以下内容:

[(${variable})]
Run Code Online (Sandbox Code Playgroud)

转义简写语法是

[[${variable}]]
Run Code Online (Sandbox Code Playgroud)

[但是如果你用常规的方括号更改内部方括号,(HTML 就不会被转义。

标签内的示例:

<div>
    [(${variable})]
</div>
Run Code Online (Sandbox Code Playgroud)