Grails 4中如何使用JSON View渲染domain对象Map并传递模型参数
解决方案
问题原因
你此前传参不生效有两个原因:
- 模板文件名拼写错误:你将
breakfast误写为breaskfast,导致系统找不到对应的子模板。 - 直接渲染Map集合时,默认只会将Map的每个Value作为子模板的默认入参,额外参数需要通过渲染闭包追加到每个元素的模型中。
修复步骤
- 先修正模板文件名和路径:将
/breaskfast/_breaskfast.gson改为/breakfast/_breakfast.gson,保持和类名一致。 - 修改
_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
相关产品推荐
相关产品推荐

