java - springTemplateEngine 中的转义引号

标签 java spring special-characters template-engine

我有一个使用 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>

关于java - springTemplateEngine 中的转义引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50089410/

相关文章:

java - 安卓NDK : Application targets deprecated ABI(s): armeabi error after update NDK

java - 如何遍历字符串数组中的所有字符

java - Spring Boot应用程序无法启动?

java - 更改 hibernate.cfg.xml 运行时 - 第一部分

r - 这个空格像千位分隔符是什么特殊字符?

java - 如何使用 hibernate 或 jpa 动态生成实体集合?

java - GWT:地点、历史和 MVP 示例

Python 脚本无法正确编码特殊的 Unicode 字符

java - 如何使用基于组的@Validated 注释验证方法参数

java - Forbidden 您无权访问搜索特殊字符