我的班级结构如下:
class A {
...
}
class B extends A {
...
}
class C extends A {
...
}不,在控制器中,我正在获取混合类型对象的列表:
A[] objects = bethodTpFetchTheList()在视图中,我需要呈现整个列表,但我需要为不同类型使用不同的模板。
有可能吗?
当我只有一个类型时,我通常以这种方式呈现json:
json tmpl.object(objects)是否有一种方法可以手动遍历列表并根据类型做出决策?
一些进展,,所以我到这里:
json utilizations, { ToolUtilization utilization ->
if (utilization.type == ToolType.TOOL_40_PRINCIPLES) {
tmpl.'/fortyPrinciplesUtilization/utilization'(utilization)
} else if (utilization.type == ToolType.RRM){
tmpl.'/rrmUtilization/utilization'(utilization)
}
}它有点工作,但它呈现空的物体..。
更多的进展
看起来,如果我使用g.inline,它会部分工作,但它不会获取模板。所以,如果我这么做:
json(utilizations) { ToolUtilization utilization ->
if (utilization.type == ToolType.TOOL_40_PRINCIPLES) {
g.inline(utilization) <= here it renders the object with a default renderer.
} else if (utilization.type == ToolType.RRM){
g.inline(template:'/rrmUtilization/utilization', model:[utilization: utilization])
}
}另一个定义了模板,生成一个空对象。
发布于 2018-10-25 18:21:56
这确实取决于细节,但这可能会有所帮助。
理想的做法是将数据组织到控制器或服务层中的单独列表中,并保持视图层更简单,但要回答所问的问题,https://github.com/jeffbrown/renderjsonobjects的项目展示了一种方法。
感兴趣的档案:
package renderjsonobjects
class DemoController {
static responseFormats = ['json', 'xml']
def index() {
// the intent here is just to simulate a list of
// instances of different types...
def results = []
results << new Person(name: 'Zack')
results << new Address(town: 'St. Louis')
results << new Person(name: 'Matt')
results << new Address(town: 'San Jose')
respond view: 'index', model: [theData: results]
}
}person.gson是一个用于呈现Person的模板。
import renderjsonobjects.Person
model {
Person person
}
json {
name person.name
}address.gson是用于呈现Address的模板。
import renderjsonobjects.Address
model {
Address address
}
json {
town address.town
}https://github.com/jeffbrown/renderjsonobjects/blob/master/grails-app/views/demo/index.gson在异构List上迭代,并为不同类型呈现不同的模板。同样,这可能并不是真正解决你真正问题的最好办法,但这是一种达到目的的方法。
import renderjsonobjects.Address
import renderjsonobjects.Person
json {
Map theModel = (Map)binding.variables.model
List data = (List)theModel.theData
people tmpl.person(data.findAll { it instanceof Person })
addresses tmpl.address(data.findAll { it instanceof Address})
}它会呈现出这样的东西:
$ curl http://localhost:8080/demo
{"people":[{"name":"Zack"},{"name":"Matt"}],"addresses":[{"town":"St. Louis"},{"town":"San Jose"}]}基于注释的更新:
见https://github.com/jeffbrown/renderjsonobjects/commit/13aea5db090cd38a2039e08fb9b675630d5bf565。
这使得https://github.com/jeffbrown/renderjsonobjects/blob/master/grails-app/views/demo/index.gson看起来如下所示:
json (((Map)binding.variables.model).theData)这样做的结果如下:
[[{"name":"Zack"},{"town":"St. Louis"},{"name":"Matt"},{"town":"San Jose"}]]我认为这满足了所提出的问题。如果您希望看到JSON的结构不同,如果您可以提供所需的输出,这将有所帮助。
https://stackoverflow.com/questions/52984001
复制相似问题