Grails Cookbook - A collection of tutorials and examples

Grails each Tag Examples

This will show examples on how to use the Grails each tag(<g:each>). This tag will iterate over each element of a collection.

Attribute: in

At the minimum, the in attribute should be specified for the Grails each tag. Each item can be referenced by it. Here is a simple example over a hard-coded list.

<g:each in="${['Cat', 'Dog' ,'Elephant']}">
    Animal: ${it} <br/>
</g:each>
This code will display this:
Animal: Cat
Animal: Dog
Animal: Elephant 

Attribute: var

For readability, we can specify the var attribute. This will replace the it in our inner expressions. Here is an example:
<g:each var="animal" in="${['Cat', 'Dog' ,'Elephant']}">
    Animal: ${animal} <br/>
</g:each>
The code will render the same result as the first sample above.

Attribute: status

The status attribute can be specified also. This will be the variable name that holds the index of the current element. Here is an example:
<g:each var="animal" in="${['Cat', 'Dog' ,'Elephant']}" status="counter">
    ${counter}. Animal: ${animal} <br/>
</g:each>
The code will display this output. As you can see, the index is zero-based - meaning it will start from the value 0.
0. Animal: Cat
1. Animal: Dog
2. Animal: Elephant 

We can just adjust our code to start with one:

<g:each var="animal" in="${['Cat', 'Dog' ,'Elephant']}" status="counter">
    ${counter+1}. Animal: ${animal} <br/>
</g:each>
The code will display this:
1. Animal: Cat
2. Animal: Dog
3. Animal: Elephant 

Iterate Over Numbers

We can also use the Grails each tag to iterate over a series of numbers
<g:each var="number" in="${(5..10)}">
    Number: ${number} <br/>
</g:each>
The code will display this:
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
Number: 10 

This can be useful when joined with some logic. For example, here is the code to display the first 10 odd numbers.

<g:each var="number" in="${(1..10)}">
    Odd Number: ${number*2-1} <br/>
</g:each>
Here is the output:
Odd Number: 1
Odd Number: 3
Odd Number: 5
Odd Number: 7
Odd Number: 9
Odd Number: 11
Odd Number: 13
Odd Number: 15
Odd Number: 17
Odd Number: 19 

Iterate Over Domain Objects

The most common scenario for using Grails each tag is to display information over a list of domain instances.

Here is an example controller and gsp code:

class PersonController {
    def list() {
        [people:Person.list()]
    }
}

<g:each var="person" in="${people}">
    <p>Last Name: ${person.lastName}</p>
    <p>First Name: ${person.firstName}</p>
</g:each>

Other Grails Tag Examples


Tags: each, Grails Tag