我有一个使用 springTemplateEngine 生成非 html 文本的方法。 我的模板如下所示:
some text
[[${variable}]]
但是当我运行模板引擎时,将 variable
设置为带引号的字符串:
string with "" quotes
引号被替换为 html 代码:
some text
string with "" quotes
有什么方法可以避免这种行为并使实际的引号出现在结果字符串中吗?
期望的输出应该是
some text
string with "" quotes
最佳答案
根据您的变量语法,我假设您正在使用 Themeleaf 作为模板引擎。
您可以使用[(${variable})]
省略变量转义的语法。这是在 Themeleaf 3 中引入的。
请参阅 Themeleaf issue tracker 上的转义部分:
Escaping
These
[[...]]
expressions, as they did in Thymeleaf 2.1, perform an escaping operation on output. So if we have atitle
variable withString
value"this & that"
, this:<p>Title: [[${title}]]</p>
will result in:
<p>Title: this & that</p>
But what if we need unescaped output? We might have a
comment
variable with valueThis is a <strong>great</strong> song!
that we know contains HTML (see those<strong>
tags) that we want to output without being escaped...In such case we can use an unescaped output expression, with syntax
[(...)]
(note the inner parentheses instead of brackets). So:<p>Title: [[${title}]]</p> <p>Description: [(${description})]</p>
...will result in:
<p>Title: this & that</p> <p>Description: This is a <strong>great</strong> song!</p>
We see therefore how the above is the exact equivalent to:
<p>Title: <th:block th:text="${title}"/></p> <p>Description: <th:block th:utext="${description}"/></p>
关于java - springTemplateEngine 中的转义引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50089410/