使用 GSP 表达式内的变量引用 Groovy Map
我正在尝试减少 Grails 应用程序中的一些重复的 GSP 代码。以下代码按预期工作:
<g:textField name="recordValues.0.name" value="${recordValues?.get(0)?.name}"/>
<g:textField name="recordValues.0.age" value="${recordValues?.get(0)?.age}"/>
[edit]recordValues.0.age
实际上是一个 Map 而不是类属性,正如我最初所说的那样。
但是,当我尝试使用 list 枚举动态设置其中一堆时,不会评估 value 属性:
<g:each in="${fields}" var="prop">
<g:textField name="recordValues.0.${prop}" value="${recordValues?.get(0)?.prop}"/>
</g:each>
看起来 value 属性正在寻找名为的 property 映射键“prop”并且没有将其作为变量进行评估。我尝试过使用和不使用 ?.get(0)[prop]
之间的 recordValues?.get(0)[prop]
但它没有编译。
是否有一些我可以使用变量作为参数来调用的动态方法或者更简单的解决方案?
I'm trying to reduce some repetitive GSP code in my Grails app. The following code works as expected:
<g:textField name="recordValues.0.name" value="${recordValues?.get(0)?.name}"/>
<g:textField name="recordValues.0.age" value="${recordValues?.get(0)?.age}"/>
[edit]recordValues.0.age
is actually a Map not a class property, as I originally stated.
However when I try to dynamically set a bunch of these with a list enum, the value attribute is not evaluated:
<g:each in="${fields}" var="prop">
<g:textField name="recordValues.0.${prop}" value="${recordValues?.get(0)?.prop}"/>
</g:each>
It appears the value attribute is looking for the property Map key called "prop" and is not evaluating it as a variable. I've tried recordValues?.get(0)[prop]
with and without ?
between but it didn't compile.
Is there some dynamic method I can call with the variable as an argument or an even easier solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最后自己整理了一下。感谢 codespace 让我再次检查代码,并注意到它是我试图引用的 Map,而不是对象属性。我使用枚举的事实使问题变得困惑,因为使用常规的
map.get(var)
不起作用,我需要map.get(var.name())
相反(也许我会将其编码为枚举内的字符串字段以避免这种情况)。这是解决方案:
Sorted it myself in the end. Thanks to codespace for making me check the code again and noticing it was a Map I was trying to reference, not an object property. The fact I was using an enum confused the issue as using the regular
map.get(var)
did not work, I neededmap.get(var.name())
instead (maybe I'll encode it as a String field inside the enum to avoid this).Here's the solution: