If you have collections of objects you often need to sort and filter them in some way. GSP supports the
findAll and
grep for this task:
Stephen King's Books:
<g:findAll in="${books}" expr="it.author == 'Stephen King'">
<p>Title: ${it.title}</p>
</g:findAll>
The
expr
attribute contains a Groovy expression that can be used as a filter. Speaking of filters the
grep tag does a similar job such as filter by class:
<g:grep in="${books}" filter="NonFictionBooks.class">
<p>Title: ${it.title}</p>
</g:grep>
Or using a regular expression:
<g:grep in="${books.title}" filter="~/.*?Groovy.*?/">
<p>Title: ${it}</p>
</g:grep>
The above example is also interesting due to its usage of GPath. GPath is Groovy's equivalent to an XPath like language. Essentially the
books
collection is a collection of
Book
instances. However assuming each
Book
has a
title
, you can obtain a list of Book titles using the expression
books.title
. Groovy will auto-magically go through the list of Book instances, obtain each title, and return a new list!