recoInrelax
recoInrelax

Reputation: 707

Grails iterate over objects in the controller

In Grails, to display a list of something in a table, i normally do the following:

My controller is

thingController {

def temp2 = something.findAllByXXX(yyy)

[temp : temp2]
}

And in my view i have:

<g:each var="it" in="${temp}">
${it.someThing}
${it.someThingSomething}
<g:each>

I don't know if this is the best approach. Is it possible to do this exact same thing, but instead of calling all the objects, and then in the gsp iterate over them, do this all controller-side. Meaning, instead of passing all the objects to the view, pass single objects.

Upvotes: 0

Views: 749

Answers (2)

ataylor
ataylor

Reputation: 66109

It's possible, but I don't think it's a good idea unless it's for a very specific reason. For example, if you always expect two objects from your query, and they need to be display differently, then you might want to have a model like [object1: temp2[0], object2: temp2[1]].

A good way to structure views to avoid the clutter of iteration is with templates. You can have a view like this:

<g:each var="it" in="${temp}">
  <g:render template="someThing" model="[someThingInstance: it]"/>
</g:each>

And a template _someThing.gsp that displays a single object:

<div>${someThingInstance.field1}</div>
<div>${someThingInstance.field2}</div>

Upvotes: 0

D&#243;nal
D&#243;nal

Reputation: 187399

I don't know if this is the best approach. Is it possible to do this exact same thing, but instead of calling all the objects, and then in the gsp iterate over them, do this all controller-side. Meaning, instead of passing all the objects to the view, pass single objects

I don't think I understand what your proposing as an alternative to your code above. But AFAIK the code above is the most common way to display a list of items in a GSP, so unless it's causing you a specific problem, I wouldn't bother looking for alternatives.

Upvotes: 2

Related Questions