combining literals with variables in JSON (CDATA) with conditional statements

54 Views Asked by At

I try to build a dynamic ld+JSON by using thymeleaf. Hereby I use conditional statements, what is basically working. However, all variables inside the conditional statements are not parsed.

<script type="application/ld+json" >

    /*<![CDATA[*/

    {
      "@context": "https://schema.org",
      "@graph": [
        {
          "@type": "Article",
          "@id": "https://website.de/quack/[[${quack.id}]]/#article",
          "publisher": { "@id": "[[${article.nickname}]]" },
          [( ${article.primaryImage} == null ? '' : '"image": { "@id": "https://website.de/quack/${quack.id}/#primaryimage" },
          "thumbnailUrl": "${article.primaryImage}",')]
          "inLanguage": "[[${quack.language}]]"
        }       
      ]
    };

    /*]]>*/

  </script>

Result:

{...
          "primaryImageOfPage": { "@id": "https://website.de/quack/${quack.id}/#primaryimage" },
          "image": { "@id": "https://website.de/quack/${quack.id}/#primaryimage" },
...}

What do I miss, to combine conditional statement with correct parsing inside the statement?

1

There are 1 best solutions below

0
On

The keyword is literal substitution

So what finally worked for me is using pipes instead of single quotes, which enables the correct parsing of all variables:

[( ${article.primaryImage} == null ? '' : |"image": { "@id": "https://website.de/quack/${quack.id}/#primaryimage" },
          "thumbnailUrl": "${article.primaryImage}",| )]

See also this thread: Thymeleaf - Unquoting a part of inline JavaScript expression