在 springTemplateEngine 中转义引号

Escape quotes in springTemplateEngine

我有一个使用 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 a title variable with String value "this & that", this:

<p>Title: [[${title}]]</p>

will result in:

<p>Title: this &amp; that</p>

But what if we need unescaped output? We might have a comment variable with value This 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 &amp; 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>