Grails Cookbook - A collection of tutorials and examples

Grails collect Tag Examples

This will show examples on how to use the Grails collect tag(<g:collect>). This tag is similar to each tag and it iterates over each element of a collection. The difference is the added attribute expr.

Required attributes: in and expr

By default, in and expr attributes are required when using Grails collect tag.

  • in - the collection/list to iterate over
  • expr - an expression or logic to generate a derived value.
Here is a quick example:
<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

Attributes: var

For readability, we can specify the var attribute. This will replace the it in our inner expressions. Here is an example:
<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.

Iterate Over Numbers

We can also use the Grails collect tag to iterate over a series of numbers. For example:
<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
19
The expr derived the odd numbers from sequential list of numbers.

Iterate Over Domain Objects

The most common scenario for using Grails collect tag is to display information over a list of domain instances. Here is an example:
<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()]
    }
}


Other Grails Tag Examples


Tags: collect, Grails Tag