Setting freemarker template from classpath

前端 未结 5 1780
野性不改
野性不改 2020-12-08 19:38

I have a web application that I need to manually obtain a Freemarker template - the template is obtained via a class in a library project, but the actual tpl file is contain

相关标签:
5条回答
  • 2020-12-08 20:02
    freemarkerConfiguration = new Configuration();
    freemarkerConfiguration.setClassForTemplateLoading(this.getClass(), "");
    Template freemarkerTemplate = freemarkerConfiguration.getTemplate("template.tpl");
    

    Use this method to load the classes from the package where your class is located, so if your class is

    org.foo.SomeClass the templates will be looked for in /org/foo in the classpath. This keeps your templates stored with the class that uses/loads them.

    0 讨论(0)
  • 2020-12-08 20:08

    In 2017, the following is deprecated:

    Configuration conf = new Configuration();
    

    We should pass freemarker.template.Version to the constructor:

    Configuration conf = new Configuration(new Version(2, 3, 23));
    conf.setClassForTemplateLoading(Application.class, "/views");
    

    where the version numbers refer to the current version of FreeMarker.

    The views directory is located in src/main/resources.

    0 讨论(0)
  • 2020-12-08 20:11

    Use the following config and place it in application properties.

    spring.freemarker.template-loader-path=
    
    0 讨论(0)
  • 2020-12-08 20:16

    this is what ended up working for me:

    freemarkerConfiguration = new Configuration(Configuration.VERSION_2_3_28);
    freemarkerConfiguration.setClassForTemplateLoading(this.getClass(), "/");
    Template freemarkerTemplate = freemarkerConfiguration.getTemplate("email/vendor.tpl");
    
    0 讨论(0)
  • 2020-12-08 20:26

    If you are using Struts 2 and the Conventions plugin, wuntee's solution doesn't seem to work: setClassForTemplateLoading in turn creates an instance of ClassTemplateLoader which doesn't find files in jars no matter what path prefix is specified.

    Instead, create an instance of StrutsClassTemplateLoader. (I do this in a custom sub-class of FreemarkerManager in its getTemplateLoader method.) It takes no parameters, so presumably it just knows how Struts and Conventions do things.

    0 讨论(0)
提交回复
热议问题