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
<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.
<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
<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
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>