Freemarker Template to access Freemarker files from the path WEB-INF\ftl\

2.3k Views Asked by At

I have two different requirements to use Freemarker Templates. One is to print some portion of the webpage and the other is to generate an customized HTML file. I have placed all the FTL files under the path WEB-INF/ftl/ The web application pulls the correct FTL file from the above location and prints the web page. When I had to generate the HTML file, the Freemarker is not able to locate the respective FTL file.

I tried to keep that particular FTL file under resources/ftl/, but still it could not pick up the file. I created a package under the src and placed the FTL. Maven does not take that package as it does not have java files in it.

Configuration cfg = new Configuration();
    cfg.setClassForTemplateLoading(this.getClass(), "");
    Template template = cfg.getTemplate("helloworld.ftl");

I can think of fixing this in two different ways. One way is to keep the file inside the project or in the classpath so as to be picked up by Freemarker. Other way is to get it as an InputStream and pass it to Freemarker. But I dont see any methods to accept the file as an InputStream or File.

ServletActionContext.getServletContext().getResourceAsStream("WEB-INF/ftl/helloworld.ftl");

Can you please let me know how to fix this issue?

1

There are 1 best solutions below

0
On

I am able to fix this on my own.

There is a method available in the configuration where you can set the Template location and ServletContext.

cfg.setServletContextForTemplateLoading(context, "WEB-INF/ftl");

You just need to pass the servletContext object to the above method with the FTL location. When you process the template by the following code, it will just pick up the file and process it.

Template template = cfg.getTemplate("helloworld.ftl");