2

I am trying to find an HTML template solution for a Java web application. I need the flexibility to load templates from whatever sources I choose as most of them will likely be in a custom database. In my search I stumbled upon StringTemplate 4, however all of the examples I see require that the user put template files on disk.

I have noticed that STGroup can be instantiated without specifying a file or directory, however using the defineTemplate method does not seem to be a substitute for using file based templates. Unfortunately in all my tests with defineTemplate I have failed to get attributes to work. This all feels like I'm guessing in the dark.

Is StringTemplate the right library for this? Is there another one that would work better?

I'm starting to consider developing my own.

Bernard Igiri
  • 1,272
  • 2
  • 18
  • 33

2 Answers2

2

I figured it out...

import org.stringtemplate.v4.*;
import net.sf.json.*;

class STExampleApp {

        public static void main(String args[]) {
                String template = "decl(type, name, value) ::= \"<type> <name><init(value)>;\"\n"
                                + "init(v) ::= \"<if(v)> = <v><endif>\"";
                STGroup views = new STGroupString(template);
                ST decl = views.getInstanceOf("decl");
                decl.add("type", "int");
                decl.add("name", "x");
                decl.add("value", 12);
                System.out.println(decl.render());
        }

}

No file loading necessary. I learned this from: How to format decimal numbers with StringTemplate (ST) in Java?

Community
  • 1
  • 1
Bernard Igiri
  • 1,272
  • 2
  • 18
  • 33
1

I would just pass the template to a ST() constructor like this:

@Test public void testNullAttr() throws Exception {
    String template = "hi <name>!";
    ST st = new ST(template);
    String expected =
        "hi !";
    String result = st.render();
    assertEquals(expected, result);
}
Terence Parr
  • 5,912
  • 26
  • 32