StringTemplates in Groovy
I was looking for some some string templating in Groovy a while back and found that Groovy supports it nicely, including something called
SimpleTemplateEngine, which seemed exactly what I needed. But I soon sat scratching my head, trying to figure out what was happening. Even Mr. Haki didn’t help me. It seemed that everyone’s explanation was too, well, simple.
This was my initial attempt:
“Huh?” I said as I saw the strange exception pop up. The error didn’t help me figure out what I did wrong. I went back and forth between my code and the examples several times before the light-bulb went off. You have to use single-quoted strings (Java Strings) instead of double-quoted strings (GStrings). All the examples have that, but no one pointed that out specifically for unobservant people like me.
So then I made a working version:
That worked nicely. Of course, I don’t usually work in Maps but in my own objects. So I tried my first instinct which was the
properties method. And, lo, and behold, it worked!
Naturally, I wasn’t going to go through the work of defining an engine and template to just use once. Again this is not something anyone shows but it’s pretty simple:
And there you go — more information that you probably wanted to know about Groovy’s