【问题标题】:How to set dynamic JSON String in Thymeleaf如何在 Thymeleaf 中设置动态 JSON 字符串
【发布时间】:2020-06-23 07:25:14
【问题描述】:

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

根据i18next-jquery introduction - 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}"}|'

【问题讨论】:

  • 不是动态版没有双引号的问题吗?所以也许试试:th:attrappend="data-i18n-options='{\"WHERE\": \"'+ ${country} +'\"}'" ?
  • @WimDeblauwe 我试过你的方法,但显示“TemplateInputException:模板解析期间发生错误”。虽然它不起作用,但我要感谢您的回复,这激励我找到解决方案。
  • 请添加您的解决方案作为答案,我会投赞成票。

标签: json thymeleaf i18next


【解决方案1】:

请试试这两个:

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

【讨论】:

    猜你喜欢
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 2015-06-25
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    相关资源
    最近更新 更多