【问题标题】:Escape quotes in springTemplateEnginespringTemplateEngine 中的转义引号
【发布时间】:2018-04-29 17:27:42
【问题描述】:

我有一个使用 springTemplateEngine 生成非 html 文本的方法。 我的模板如下所示:

some text
[[${variable}]]

但是当我运行模板引擎并将variable 设置为带引号的字符串时:

string with "" quotes

引号替换为html代码:

some text
string with "" quotes

有什么办法可以避免这种行为并在结果字符串中出现实际的引号?

期望的输出应该是

some text
string with "" quotes

【问题讨论】:

    标签: java spring special-characters template-engine


    【解决方案1】:

    根据您的变量语法,我假设您使用 Themeleaf 作为模板引擎。

    您可以使用[(${variable})] 语法来省略变量的转义。这是在 Themeleaf 3 中引入的。

    请参阅Themeleaf issue tracker 上的转义部分:

    转义

    这些[[...]] 表达式,就像它们在 Thymeleaf 2.1 中所做的那样,对输出执行转义操作。所以如果我们有一个title 变量,String"this & that",这个:

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

    将导致:

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

    但是如果我们需要 非转义 输出怎么办?我们可能有一个 comment 变量,其值为 This is a &lt;strong&gt;great&lt;/strong&gt; song!,我们知道它包含我们想要输出而不被转义的 HTML(请参阅那些 &lt;strong&gt; 标记)......

    在这种情况下,我们可以使用 未转义的输出表达式,语法为 [(...)](注意内括号而不是括号)。所以:

    <p>Title: [[${title}]]</p>
    <p>Description: [(${description})]</p>
    

    ...将导致:

    <p>Title: this &amp; that</p>
    <p>Description: This is a <strong>great</strong> song!</p>
    

    因此,我们看到上面的内容完全等同于:

    <p>Title: <th:block th:text="${title}"/></p>
    <p>Description: <th:block th:utext="${description}"/></p>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多