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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23156585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:06:07  来源:igfitidea点击:

Process thymeleaf variable as html code and not text

javathymeleaf

提问by Alexandru Severin

I'm using Thymeleaf to process html templates, I understood how to append inline strings from my controller, but now I want to append a fragment of html code into the page.

我正在使用 Thymeleaf 处理 html 模板,我了解如何从我的控制器附加内联字符串,但现在我想将一段 html 代码附加到页面中。

For example, lets stay that I have this in my java application:

例如,让我在我的 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);

What do I need to write in the html page so that it would be replaced by the "n" variable and be processed as html code instead of it being encoded as text?

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

采纳答案by michal.kreuzman

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

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

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