javagoogle-app-enginestringtemplate-4

Why do I get a NullPointerException with seemingly simple StringTemplate code?


I'd like to use StringTemplate 4 to render views in my Google App Engine app.

In my Controller (I'm using Slim3 MVC framework if it matters), I have this code:

STGroup group = new STGroupDir("templates/default",'$','$');
ST stPage = group.getInstanceOf("page");
stPage.add("title", "Welcome to my Page!");
stPage.add("title_h1", "So glad you came!");
response.getWriter().print(stPage.render());
return null;

I have a single ST file named page.st in the directory war/templates/default

When I run this code, I get the following NullPointerException. When viewing the ST code online, it appears to be related to the path to the file. The path to the template file is accessible via web browser by navigating to it.

Here's the relevant part of the exception:

java.lang.NullPointerException
    at org.stringtemplate.v4.STGroup.loadTemplateFile(STGroup.java:656)
    at org.stringtemplate.v4.STGroupDir.loadTemplateFile(STGroupDir.java:176)
    at org.stringtemplate.v4.STGroupDir.load(STGroupDir.java:136)
    at org.stringtemplate.v4.STGroup.lookupTemplate(STGroup.java:230)
    at org.stringtemplate.v4.STGroup.getInstanceOf(STGroup.java:165)

Edit:

I figured out my file was formatted improperly. If your page.st file is a valid format, you will not get the NullPointerException. Here is an example of a valid page.st file. Above, I have added what it takes to render this page from a servlet.

page(title,title_h1)::=<<
<!DOCTYPE html>
    <head>
      <title>$title$</title>
    </head>
    <body>
    <h1>$title_h1$</h1>
    </body>
</html>
>>

Solution

  • It turns out, the format of my page.st file was incorrect. In this case, you get the NullPointerException. I have updated my question to include a proper format for page.st.