We have been using string template in java for a while and have just upgraded to String Template 4.0.7.
In string template 3.2 (The version we were previously using), I had a string template file called stringtemplate.st
in src/main/resources
, and we just had a group called anything we liked as it didn't seem to make a difference, and loaded the template like so:
final StringTemplateGroup group = new StringTemplateGroup("groupName");
final StringTemplate xmlMessage = group.getInstanceOf("stringtemplate");
After updating to 4.0.7, if you wish to load individual files, my understanding is that you need to have a STGroupDir
object with the name of a folder where the templates are located.
So, I moved the stringtemplate file to src/main/resources/templates
and changed the above code to this:
final URL url = Thread.currentThread().getContextClassLoader().getResource("templates");
final STGroup group = new STGroupDir(url.getPath(), '$', '$');
final ST xmlMessage = group.getInstanceOf("stringtemplate");
When I then try to populate the string template, this causes a null pointer to be thrown, and it appears that no templates are found.
My understanding was that the String passed to the STGroupDir constructor should be the directory that the template files are located, and that if the template files are not found there, the classpath would be searched anyway. Am I fundamentally misunderstanding something? Any suggestions as to what I am doing wrong?
Sorry to answer my own question so soon, but it appears I had got the syntax in the .st file wrong. I had declared the arguments at the top, but I hadn't realised the x in the examples signified the file name. So, I had:
x(message) ::= <<
<?xml version="1.0" encoding="UTF-8"?> ...
>>
I replaced this with:
stringtemplate(message) ::= <<
<?xml version="1.0" encoding="UTF-8"?> ...
>>
and it worked. Thanks to the answer to this question for helping me work it out.