Skip to content
Advertisement

Thymeleaf LD+JSON output quote escaped

I am generating LD+JSON string on server and I need to output it on client using Thyemeleaf.

Generated JSON looks like this on server:

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

As you can see the text is properly formatted on server. I render it on client like this:

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

But the output in HTML looks like this:

{

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

As you can see <a href is not properly escaped. For some reason it adds &quot; into the href attribute and does not escape double quote.

How can I force Thymeleaf to output the string exactly as it should look like?

Advertisement

Answer

To display the literal text in your HTML page, you can use th:inline="text" – and to preserve the line breaks you can also use white-space: pre-wrap;:

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

The resulting HTML display is this on the browser page:

enter image description here

See text inlining for reference.

Don’t leave any white space between the > in the div tag and the [ at the start of the Thymeleaf expression – otherwise that will become white space on the HTML page.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement