springspring-mvcthymeleaf

Adding Custom Thymeleaf Template Resolver to Spring Boot


By Default, Spring Boot Application searches thymeleaf templates under classpath://templates

How do we add one more resolver For E.g, We need to search templates from local directory like "c:\MyTemplates" using FileTemplateResolver ?


Solution

  • You can add more template resolvers on the TemplateEngine either by invoking the setTemplateResolvers method or by invoking the addTemplateResolver method with your FileTemplateResolver.

    @Configuration
    public class ThymeleafExtension {
    
        @Autowired
        private SpringTemplateEngine templateEngine;
    
        @PostConstruct
        public void extension() {
            FileTemplateResolver resolver = new FileTemplateResolver();
            resolver.setPrefix("D:\\templates\\");
            resolver.setSuffix(".html");
            resolver.setTemplateMode("HTML5");
            resolver.setOrder(templateEngine.getTemplateResolvers().size());
            resolver.setCacheable(false);
            templateEngine.addTemplateResolver(resolver);
        }
    }