Thymelaf-th:每个进入JSON-LD



我希望循环使用Thymelaf变量数组来生成JSON-LD(使用Schema.org),类似于谷歌的商店部门示例。

我知道你可以用HTML在Thymelaf中循环一个数组,如下所示:

<tr th:each="prod : ${prods}">
  <td th:text="${prod.name}">Onions</td>
  <td th:text="${prod.price}">2.41</td>
  <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>

有没有一种方法可以在JSON-LD格式中实现同样的功能?

我担心这不可能在客户端上实现。您需要在服务器上准备JSON,并将其作为字符串发送到客户端。

因此,为JSON准备实体,如下所示:

@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class FaqAnswerLdJson extends AbstractLdJson implements Serializable {
    @JsonProperty("name")
    private String name;
    @JsonProperty("price")
    private String price;
    ...
}

然后将其序列化为服务器上的JSON,并放入模型中。

在客户端上,你可以这样渲染:

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

最新更新