Quantcast
Channel: T. C. Mits 108 » java
Viewing all articles
Browse latest Browse all 36

Groovy template fails if language keywords used

$
0
0

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

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());
}
Listing 1

Below is an example of this.

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
Listing 2

Results in:

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

Now change the expression to $pack:

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
Listing 3

And, the result is:

package a/b/c;

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”

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Viewing all articles
Browse latest Browse all 36

Trending Articles