By default, in and expr attributes are required when using Grails collect tag.
<g:collect in="${['Cat', 'Dog', 'Elephant']}" expr="${ "Hello " + it }" > <p>${it}</p> </g:collect>And this is the sample output.
Hello Cat Hello Dog Hello Elephant
<g:collect in="${['Cat', 'Dog', 'Elephant']}" expr="${ "Hello " + it }" var="greeting"> <p>${greeting}</p> </g:collect>The code will render the same result as the first sample above. Specifying the var attribute makes the Grails collect tag code easy to read at quick glance because of the logical variable name.
<g:collect in="${(5..10)}" expr="${it*2-1}" var="number"> <p>${number}</p> </g:collect>The code will display these odd numbers:
9 11 13 15 17 19The expr derived the odd numbers from sequential list of numbers.
<g:collect in="${people}" expr="${it.lastName + ", " + it.firstName}"> <p>${it}</p> </g:collect>
And here is a sample output:
Doe, John Doe, Jane Doe, Jesse Smith, Rex Smith, Roy Johnson, Amy
This code has the similar behavior as above but uses the var attribute.
<g:collect in="${people}" expr="${it.lastName + ", " + it.firstName}" var="fullName"> <p>${fullName}</p> </g:collect>
Here is the rest of the supporting code
Domain Class
class Person { String firstName String lastName int age static constraints = { } }
Bootstrap code thatinserts test data
class BootStrap { def init = { servletContext -> if (Person.count()==0) { new Person(firstName: 'John', lastName: 'Doe', age: 10).save() new Person(firstName: 'Jane', lastName: 'Doe', age: 10).save() new Person(firstName: 'Jesse', lastName: 'Doe', age: 10).save() new Person(firstName: 'Rex', lastName: 'Smith', age: 12).save() new Person(firstName: 'Roy', lastName: 'Smith', age: 12).save() new Person(firstName: 'Amy', lastName: 'Johnson', age: 8).save() } } }
Controller code
class TestController { def index() { [people:Person.list()] } }