这是以下问题:如何将映射呈现为 Grails 4 JSON 视图中的属性 https://stackoverflow.com/q/69322504/715608
我有以下 JSON 视图,我想渲染以下值mealsByPerson
地图使用_breakfast.gson
模板。另外,我希望能够通过allCaps
模型属性来自_foo.gson
to breakfast.gson
/foo/_foo.gson
import rendermapexample.Breakfast
model {
Float cost
Date date
Map<String, Breakfast> mealsByPerson
Boolean allCaps
}
json {
date date
cost cost
mealsByPerson g.render(mealsByPerson){} //HOW DO I PASS `allCaps` to this template?
// This doesn't work
// mealsByPerson g.render(mealsByPerson, model: [allCaps: true]){}
}
/breaskfast/_breaskfast.gson
import rendermapexample.Breakfast
model {
Breakfast breakfast
Boolean allCaps
}
json {
meat allCaps ? breakfast.meat.toUpperCase() : breakfast.meat
eggs allCaps ? breakfast.eggs.toUpperCase() : breakfast.eggs
side allCaps ? breakfast.side.toUpperCase() : breakfast.side
}
Foo控制器
package rendermapexample
class FooController {
static responseFormats = ['json', 'xml']
def index() {
Map<String, Breakfast> mealsByPerson = [
Tom: new Breakfast(meat: "bacon", eggs: "scrambled", side: "hashbrowns"),
Jack: new Breakfast(meat: "sausage", eggs: "over easy", side: "pancakes")
]
render template: "foo", model: [
cost: 12.34f,
date: new Date(),
mealsByPerson: mealsByPerson,
allCaps: params.boolean("allCaps")
]
}
}
所需输出
http://localhost:8080/foo
{
"cost": 12.34,
"date": "2021-09-25T01:11:39Z",
"mealsByPerson": {
"Tom": {
"eggs": "scrambled",
"meat": "bacon",
"side": "hashbrowns"
},
"Jack": {
"eggs": "over easy",
"meat": "sausage",
"side": "pancakes"
}
}
}
http://localhost:8080/foo?allCaps=true
{
"cost": 12.34,
"date": "2021-09-25T01:11:39Z",
"mealsByPerson": {
"Tom": {
"eggs": "SCRAMBLED",
"meat": "BACON",
"side": "HASHBROWNS"
},
"Jack": {
"eggs": "OVER EASY",
"meat": "SAUSAGE",
"side": "PANCAKES"
}
}
}
示例项目
https://github.com/tonyerskine/rendermapexample https://github.com/tonyerskine/rendermapexample