How to access my freemarker template (*.ftl) files stored within my src/main/resources folder from my code (Spring Boot application) ?
I tried the following
freemarker.template.Configuration config = new Configuration(); configuration.setClassForTemplateLoading(this.getClass(), "/resources/templates/");
and getting the following exception
freemarker.template.TemplateNotFoundException: Template not found for name "my-template.ftl".
The root of the classpath is src/main/resources
, change the path to
configuration.setClassForTemplateLoading(this.getClass(), "/templates/");
I was facing "freemarker.template.TemplateNotFoundException: Template not found for name..." issue. My code was correct but I forgot to include /templates/ directory in pom.xml. So below code fixed the issue for me. I hope this helps.
AppConfig.java : @Bean(name="freemarkerConfiguration") public freemarker.template.Configuration getFreeMarkerConfiguration() { freemarker.template.Configuration config = new freemarker.template.Configuration(freemarker.template.Configuration.getVersion()); config.setClassForTemplateLoading(this.getClass(), "/templates/"); return config; } EmailSenderServiceImpl.java: @Service("emailService") public class EmailSenderServiceImpl implements EmailSenderService { @Autowired private Configuration freemarkerConfiguration; public String geFreeMarkerTemplateContent(Map<String, Object> dataModel, String templateName) { StringBuffer content = new StringBuffer(); try { content.append(FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate(templateName), dataModel)); return content.toString(); } catch(Exception exception) { logger.error("Exception occured while processing freeMarker template: {} ", exception.getMessage(), exception); } return ""; } } pom.xml : <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <scope>compile</scope> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/resources/</directory> <includes> <include>templates/*.ftl</include> </includes> </resource> <resource> <directory>src/main/</directory> <includes> <include>templates/*.ftl</include> </includes> </resource> </resources> </build>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With