试图生成一个在freemarker中变成变量名称的字符串或“派生变量名称”的字符串。
我正在使用数据指导性或列表来吸收几个值,其中我不知道会有多少个值,我想尝试通过它们列表,并在列表中创建几个变量,如果您愿意的话。
<#list 1..10 as x>
<#-- the next line doesn't work, but what i'm trying to fix -->
<#assign .vars['VAR'+x?string] = rand(100) />
</#list>
但是我可以以这种方式列出它们。
<#list 1..10 as x>
${.vars['VAR'+x?string]}
</#list>
分配的文档说:
名称:变量的名称。这不是表达。但是,可以是 以字符串字面形式写成,如果变量名称很有用 包含保留的字符,例如&lt; #ashign“ foo-bar” = 1&gt;。 请注意,该字符串文字不会扩展插值(如 “ $ {foo}”)。
没有办法解决这个问题吗?我想做不可能的事情吗?有什么方法可以将派生名称插入.vars ...哈希是吗?
更多的研究很接近,但没有让我到那里:
- 这个prevoius问题给出了如何读取派生变量的方法,但是我需要写/创建派生的变量。
- 这个prevoius问题表明,我可以使用字符串来分配变量,并重新介绍我们在第一个链接中看到的内容。 freemarker模板中的变量名称
I'm using a data-directive or list to pull in several values, of which, I don't know how many there will be, and I want to try and list through them, and create several variables in the list if you will.
<#list 1..10 as x>
<#-- the next line doesn't work, but what i'm trying to fix -->
<#assign .vars['VAR'+x?string] = rand(100) />
</#list>
But I can list them back out that way.
<#list 1..10 as x>
${.vars['VAR'+x?string]}
</#list>
The documentation for assign, says:
name: name of the variable. It is not expression. However, it can be
written as a string literal, which is useful if the variable name
contains reserved characters, for example <#assign "foo-bar" = 1>.
Note that this string literal does not expand interpolations (as
"${foo}").
Is there no way around this? Am I trying to do the impossible? Is there some way I can insert a derived name into the .vars... Hash is it?
A little more research that was close, but didn't get me there:
- This prevoius question gives how to READ the derived variable, but I need to WRITE/CREATE the derived variable.
FreeMarker get variable value by concatenating another variable value - This prevoius question shows that I can use a string to assign a variable and re-iterates what we saw in the first link.
Variable name in Freemarker Template Language
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最终,我相信我的解决方案的正确方法是一系列哈希:
我们特别避免
&lt; #assign my_hash = my_hash + element/&gt;
,因为此注释在文档中:Ultimately, I believe the correct way to phrase my solution was a sequence of hashes:
We specifically avoid
<#assign my_hash = my_hash + element />
because of this note in the documentation:由于freemarker无法分配收集元素(但是您可以
?map(IT - &gt; ...)
收集到另一个集合),因此唯一的方法是通过?drigent drigent :
我想知道为什么您需要分配给动态命名的变量,因为即使较小的变量,动态命名的变量也很痛苦。
As FreeMarker can't assign to elements of collections (but you can
?map(it -> ...)
a collection to another), the only way is via?interpret
:I wonder why do you need to assign to a dynamically named variables though, since reading dynamically named variables is also a pain, even if a lesser one.