首页 > 解决方案 > 如何在 Thymeleaf 中设置动态 JSON 字符串

问题描述

我在前端页面中使用 Thymeleaf,出于某种原因,我必须通过 i18next.js 而不是 spring 框架来处理 i18n。

根据i18next-jquery 的介绍 - using options in translation function,我是这样写的:

<span data-i18n="myKey" data-i18n-options='{ "WHERE": "TW" }'></span>

还有我的语言资源:

{ "myKey" : "User is from {{WHERE}}."  }

并且 html 被完美地解析并显示如下:

<span data-i18n="myKey" data-i18n-options='{ "WHERE": "TW" }'> User is from TW. </span>

但是当我通过 Thymeleaf 属性动态设置 {{WHERE}} 时,它就无法解析任何东西。


th:attrappend="data-i18n-options='{WHERE: '+ ${country} +'}'"
我也 试过 了
th:data-i18n-options="'{WHERE: '+ ${country} +'}'"
不知怎的,结果是这样的:

<span data-i18n="myKey" data-i18n-options="{WHERE: TW}">User is from  .</span>

所以我想知道在 Thymeleaf 属性中解析 json 字符串有什么想法吗?


更新:
我想分享我的解决方案,我希望它能节省别人的时间:)

th:attrappend='data-i18n-options=|{ "WHERE":"${country}"}|' 或者 th:data-i18n-options='|{ "WHERE":"${country}"}|'

标签: jsonthymeleafi18next

解决方案


请尝试以下两个:

th:attrappend='data-i18n-options=|{ "WHERE":"${country}"}|'
或者
th:data-i18n-options='|{ "WHERE":"${country}"}|'


推荐阅读