首页 > 解决方案 > Thymeleaf LD+JSON 输出报价转义

问题描述

我在服务器上生成 LD+JSON 字符串,我需要使用 Thymeleaf 在客户端上输出它。

生成的 JSON 在服务器上如下所示:

{
  "@context" : "http://schema.org",
  "@type" : "FAQPage",
  "mainEntity" : [ {
    "@type" : "Question",
    "name" : "question text",
    "acceptedAnswer" : {
      "@type" : "Answer",
      "text" : "answer text <a href=\"\">link</a> answer text."
    }

如您所见,文本在服务器上的格式正确。我在客户端上渲染它是这样的:

<script type="application/ld+json" th:utext="${faqsJson}">

但 HTML 中的输出如下所示:

{

  "@context" : "http://schema.org",
  "@type" : "FAQPage",
  "mainEntity" : [ {
    "@type" : "Question",
    "name" : "question text",
    "acceptedAnswer" : {
      "@type" : "Answer",
      "text" : "answer text <a href="\&quot;\&quot;"> answer text."
    }

如您所见<a href,没有正确转义。由于某种原因,它添加&quot;到 href 属性中并且不会转义双引号。

如何强制 Thymeleaf 完全按照它的样子输出字符串?

标签: javathymeleaf

解决方案


要在 HTML 页面中显示文字文本,您可以使用th:inline="text"- 并保留换行符,您还可以使用white-space: pre-wrap;

<div th:inline="text" style="white-space: pre-wrap;">[[${faqsJson}]]</div>

生成的 HTML 显示在浏览器页面上是这样的:

在此处输入图像描述

请参阅文本内联以供参考。

不要>在 div 标签中的 和[Thymeleaf 表达式的开头之间留下任何空白 - 否则它将成为 HTML 页面上的空白。


推荐阅读