thymeleaf 将字符串评估为变量

Posted

技术标签:

【中文标题】thymeleaf 将字符串评估为变量【英文标题】:thymeleaf evaluate string as variable 【发布时间】:2022-01-19 01:17:39 【问题描述】:

假设我有一个名为“reference”的百里香片段,它接受一个参数referenceNumber="1",在我的模型中我有“reference1_firstName”=“Bob”

<div ... th:fragment="reference(referenceNumber)">
   Reference <div th:text="$referenceNumber"/> first name is <div th:text="$'reference' + referenceNumber + '_firstName'".>
</div>

在上面明显不正确的示例中,我想打印出“Reference 1 first name is Bob”。看起来很简单,我可以用其他几种语言做到这一点,但到目前为止,我对百里香的搜索是空的

【问题讨论】:

【参考方案1】:

有几种方法可以做到这一点。

Preprocessing:

<span th:text="$reference__$referenceNumber___firstName" />

#ctx basic object:

<span th:text="$#ctx.getVariable('reference' + referenceNumber + '_firstName')" />
<span th:text="$#ctx['reference' + referenceNumber + '_firstName']" />

或者,如果您打算以这种方式访问​​变量,请使用 Map 而不是变量。

【讨论】:

感谢您的帮助,预处理就像一个魅力,然后按照您的建议,我将代码重构为引用列表并迭代它们,就像我一开始应该做的那样。谢谢!

以上是关于thymeleaf 将字符串评估为变量的主要内容,如果未能解决你的问题,请参考以下文章

将字符串评估为类变量

Template::Toolkit 不将变量评估为字符串

Thymeleaf 将 JSON 字符串作为 JSON 对象打印到 javascript 变量中

springboot页面模板thymeleaf的简单用法

03-03:springBoot 整合thymeleaf

Oracle 字符串内容评估为标识符