Search code examples
javastringtemplate-4

How do I load StringTemplates from the resource package?


I have the following package structure

src/main/resources/shiro/definitions

I'd like to load the .st files from the resources package. I can't figure out how to get the right file path for this folder.

I'd like to do something like (snippet from the docs) to load my templates:

STGroup group = new STGroupFile("shiro/definitions")
ST st = group.getInstanceOf("decl");
st.add("type", "int");
st.add("name", "x");
st.add("value", 0);
String result = st.render();

I'd also like to get templates that I can access them at runtime when I create an executable jar.


Solution

  • I must have been typing something incorrectly. I was able to get it to work.

    Given,

    src/main/resources/shiro/definitions
    -- shiro.stg
    
    src/main/resources/shiro/definitions/test
    -- decl.st
    -- init.st
    

    I can access the templates as a folder with:

    STGroup group = new STGroupDir("shiro/definitions/test");
    ST st = group.getInstanceOf("decl");
    

    I can access the group file with:

    STGroup group = new STGroupFile("shiro/definitions/shiro.stg");
    ST st = group.getInstanceOf("decl");
    

    It works!