Grails Cookbook - A collection of tutorials and examples

Groovy GString Examples

GString represents a String that may be used for template like functionality. It contains embedded values that can be evaluated lazily. For example, the GString "Hi ${name}" can be evaluated giving a value to name. Below are some examples.

Simple Groovy GString Example

First of all, GStrings should use double quotes and not single quotes. See example below.

def firstName = 'John'
def lastName = "Doe"
println '${lastName}, ${firstName}'
println "${lastName}, ${firstName}"
The first println does not use GString because it uses single quote. The second one is a GString because it uses double quotes. The output of the code will be:
${lastName}, ${firstName}
Doe, John

As seen, GString are evaluated using values from the expression inside ${}.

Multiline Groovy GString

Groovy GString can also by applied to multiline Strings. To declare multiline, it should start with triple double quotes and should end with the same. Below is an example:

def name = "John Doe"
def age = 10
def theString = """
Hi ${name}
Your age is ${age}
println theString
And this will output:
Hi John Doe
Your age is 10

GString Applied to SQL Statements

GString are nice because it can be used as a simple templating engine. For example, we can apply it to compose queries.
def people = [ [name:'John Doe', age:10], [name:'Jane Smith', age:12], [name:'Robert Johnson', age:15] ]
people.each { person ->
    println "insert into person_table(name, age) values ('${}', ${person.age})"

The output will be:

insert into person_table(name, age) values ('John Doe', 10)
insert into person_table(name, age) values ('Jane Smith', 12)
insert into person_table(name, age) values ('Robert Johnson', 15)