Thymeleaf中如何将Spring MVC模型属性转为JSON作为HTML属性值
方案1:使用Thymeleaf内置#json工具类(最推荐)
Thymeleaf 3.0+版本内置了JSON序列化工具类#json,可以直接在任意表达式位置调用,无需额外配置:
<!-- 同时演示在标签内容和HTML属性中输出JSON数组 --> <div th:each="station : ${stations}" th:data-station-codes="${#json.toString(station.codes)}" th:text="${#json.toString(station.codes)}"> </div>
渲染后的结果为:
<div data-station-codes="["CD1","CD2"]">["CD1","CD2"]</div>
属性中的双引号会自动做HTML转义,保证标签语法合法,前端读取属性值时会自动还原为标准JSON格式。
方案2:使用文本内联能力
内联语法不局限于JavaScript标签,开启th:inline="text"后,在标签内容和属性值中都可以直接使用[[${}]]语法实现JSON序列化:
<div th:each="station : ${stations}" th:inline="text" th:data-station-codes="[[${station.codes}]]"> [[${station.codes}]] </div>
渲染效果和方案1完全一致,适合习惯用内联语法的场景。
内容的提问来源于stack exchange,提问作者Teocali
相关产品推荐
相关产品推荐

