Groovy template fails if language keywords used

While using the SimpleTemplateEngine to process a template with a “$package” expression I got an error. Rename this expression to “$pack” and it works.

Puzzling. Then I looked at the source code for the template engine. Oops, forgot that Groovy uses script parsing of text to implement many powerful features, like templates. Kind of like extreme EYODF*. Thus, a snippet of the source code for SimpleTemplateEngine shown in listing 1 below, the word “package” is interpreted as the Java language keyword “package“.

[sourcecode language=”groovy” highlight=”2″]
try {
template.script = groovyShell.parse(script, "SimpleTemplateScript" + counter++ + ".groovy");
} catch (Exception e) {
throw new GroovyRuntimeException("Failed to parse template script (your template may contain an error or be trying to use expressions not currently supported): " + e.getMessage());
}
[/sourcecode]

Listing 1

Below is an example of this.

[sourcecode language=”groovy”]
def templateText = ”’package $package;”’

def engine = new groovy.text.SimpleTemplateEngine(true)
def template = engine.createTemplate(templateText)
def binding = [‘package’:’a/b/c’]

def s = template.make(binding)
println s
[/sourcecode]

Listing 2

Results in:
[sourcecode]
Caught: groovy.lang.GroovyRuntimeException: Failed to parse template script (your template may contain an error or be trying to use expressions not currently supported): startup failed:
SimpleTemplateScript1.groovy: 1: unexpected token: package @ line 1, column 23.
out.print("""package $package;""");
^

1 error
[/sourcecode]

Now change the expression to $pack:
[sourcecode language=”groovy”]
def templateText = ”’package $pack;”’

def engine = new groovy.text.SimpleTemplateEngine() // pass in true to see debug output
def template = engine.createTemplate(templateText)
def binding = [‘pack’:’a/b/c’]

def s = template.make(binding)
println s
[/sourcecode]

Listing 3

And, the result is:
[sourcecode]
package a/b/c;
[/sourcecode]

Environment

  • Groovy Version: 2.2.2 JVM: 1.7.0_25 Vendor: Oracle Corporation OS: Windows 7
  • Eclipse 4.3
  • Groovy-Eclipse Feature: 2.9.0.xx-20140228-1800-e43-SNAPSHOT

Some links

EYODF*: “Eat Your Own Dog Food”

Leave a Reply

Your email address will not be published. Required fields are marked *