将JSON传递到Thymeleaf中的数据模型属性

时间:2019-03-12 16:20:20

标签: json thymeleaf

所以我有一个像

<input type="text" />

现在出于测试目的在模板中,我需要将JSON literal 传递给该输入的数据模型属性:

JSON:

{ "disabled": true, "title": "my beautiful input" }

所以我需要这里的th:attr绑定:

<input type="text" th:attr="" />

如果我只有文字,我必须以哪种格式/转义在data-model绑定中传递th:attr

我希望Thymeleaf创建此输出:

<input type="text" data-model='{ "disabled": true, "title": "my beautiful input" }' />

我需要一个输出,允许我在前端的属性值上使用JSON.parse()

2 个答案:

答案 0 :(得分:2)

这对我有用(使用JSON.parse解析就可以了):

<input type="text" th:attr="data-model='{ &quot;disabled&quot;: true, &quot;title&quot;: &quot;my beautiful input&quot; }'" />

尽管,如果您只是对该属性进行硬编码,我看不到为什么您不仅仅使用:

<input type="text" data-model='{ "disabled": true, "title": "my beautiful input" }' />

开始(也适用于Thymeleaf)。

答案 1 :(得分:1)

您可以通过以下方式传递它:

<div th:attr="data-model=${json}">