简体   繁体   English

使用 GSP 表达式中的变量引用 Groovy Map

[英]Referencing a Groovy Map using a variable inside a GSP expression

I'm trying to reduce some repetitive GSP code in my Grails app.我试图在我的 Grails 应用程序中减少一些重复的 GSP 代码。 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. [编辑] recordValues.0.age实际上是 Map 而不是 class 属性,正如我最初所说的那样。

However when I try to dynamically set a bunch of these with a但是,当我尝试使用list列表enum, the value attribute is not evaluated:枚举,不评估 value 属性:

<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看来 value 属性正在寻找property财产Map key called "prop" and is not evaluating it as a variable. Map 键称为“prop”,并未将其作为变量进行评估。 I've tried recordValues?.get(0)[prop] with and without ?我试过recordValues?.get(0)[prop]有和没有? 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?有没有我可以用变量作为参数调用的动态方法或更简单的解决方案?

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.感谢代码空间让我再次检查代码并注意到它是我试图引用的 Map,而不是 object 属性。 The fact I was using an enum confused the issue as using the regular map.get(var) did not work, I needed map.get(var.name()) instead (maybe I'll encode it as a String field inside the enum to avoid this).我使用枚举的事实混淆了问题,因为使用常规map.get(var)不起作用,我需要map.get(var.name())代替(也许我会将其编码为字符串字段内枚举以避免这种情况)。

Here's the solution:这是解决方案:

<g:each in="${fields}" var="prop">
  <g:textField name="recordValues.0.${prop}" value="${recordValues?.get(0)?.get(prop.name())}"/>
</g:each>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM