You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Grails 4中如何使用JSON View渲染domain对象Map并传递模型参数

解决方案

问题原因

你此前传参不生效有两个原因:

  1. 模板文件名拼写错误:你将breakfast误写为breaskfast,导致系统找不到对应的子模板。
  2. 直接渲染Map集合时,默认只会将Map的每个Value作为子模板的默认入参,额外参数需要通过渲染闭包追加到每个元素的模型中。

修复步骤

  1. 先修正模板文件名和路径:将/breaskfast/_breaskfast.gson改为/breakfast/_breakfast.gson,保持和类名一致。
  2. 修改_foo.gson中mealsByPerson的渲染逻辑,在渲染闭包内给每个元素的模型追加allCaps参数:
import rendermapexample.Breakfast

model {
    Float cost
    Date date
    Map<String, Breakfast> mealsByPerson
    Boolean allCaps
}

json {
    date date
    cost cost
    mealsByPerson g.render(mealsByPerson) {
        it.allCaps = allCaps
    }
}

上述写法中,闭包的it参数对应每个要传给_breakfast.gson的模型对象,追加的allCaps属性会直接被子模板接收,即可实现你要求的根据参数切换大小写的效果。

如果想要更灵活的控制渲染逻辑,也可以手动遍历Map渲染,写法如下:

mealsByPerson {
    mealsByPerson.each { personName, breakfast ->
        "$personName" g.render(template: '/breakfast/breakfast', model: [breakfast: breakfast, allCaps: allCaps])
    }
}

内容的提问来源于stack exchange,提问作者SGT Grumpy Pants

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 07:18:04