为Thymeleaf的内联Javascript指定双引号

时间:2015-11-24 23:51:54

标签: thymeleaf json-ld

我正在尝试将一些架构标记添加到使用Thymeleaf构建的站点。我的第一个想法是使用ld + json方法:

<script type="application/ld+json" th:inline="javascript">
{
    "@context": "http://schema.org",
    "@type": "LocalBusiness",
    "address": {
      "@type": "PostalAddress",
      "streetAddress": /*[[ ${C:Location.street}]]*/,
      "addressLocality": /*[[ ${C:Location.city}]]*/,
      "addressRegion": /*[[ ${C:Location.state}]]*/,
      "postalCode": /*[[ ${C:Location.zipcode}]]*/
    },
}
</script>

但是Thymeleaf用单引号输出这些字符串,当使用https://developers.google.com/structured-data/testing-tool/

进行检查时,这显然不会验证为正确的JSON

有可能告诉Thymeleaf在这里使用双引号吗?如果所有其他方法都失败了,我可以进行HTML微数据标记,但我不愿意这样做,因为它不是那么漂亮和模块化。

2 个答案:

答案 0 :(得分:1)

我尝试使用文字模式:

<script type="application/ld+json" th:inline="text">
    {
        "@context": "http://schema.org",
        "@type": "EmailMessage",
        "potentialAction": {
            "@type": "ViewAction",
            "url": "[[ @{${url}} ]]",
            "name": "[[ #{message.button.text} ]]"
        }
    }
</script>

输出:

<script type=3D"application/ld+json" xml:space=3D"preserve">
    {
        "@context": "http://schema.org",
        "@type": "EmailMessage",
        "potentialAction": {
            "@type": "ViewAction",
            "url": "https://watch-movies.com/watch",
            "name": "Watch movie"
        }
    }
</script>

答案 1 :(得分:0)

这可能对使用html.erb

的人有所帮助
<script type="application/ld+json">
  {
      "@context": "http://schema.org",
      "@type": "EmailMessage",
      "potentialAction": {
        "@type": "ViewAction",
        "url": <%= resource.photos.first(3).map(&:url) %>,
        "name": "some text"
      }
  }
</script>

此处不会为{url}字段添加["url1", "url2", "url3"],而是[&quote;url1&quote;, &quote;url2&quote; &quote;url3&quote;]

要获得所需的结果,请使用.to_json.html_safe

<script type="application/ld+json">
  {
    "@context": "http://schema.org",
    "@type": "EmailMessage",
    "potentialAction": {
        "@type": "ViewAction",
        "url": <%= resource.photos.first(3).map(&:url).to_json.html_safe %>,
        "name": "some text"
    }
  }
</script>