Adding Custom Thymeleaf Template Resolver to Spring Boot
Asked Answered
G

3

12

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 ?

Gobbledegook answered 6/8, 2014 at 8:58 Comment(1)
I didn't know Spring boot searches for thymeleaf templates only in templates folder. I had mine in static folder and it wasn't resolving. +1Marikomaril
S
17

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);
    }
}
Scheffler answered 6/8, 2014 at 13:17 Comment(2)
The Template repository implementation does not seem to honor the Order property: at line 203 there is no sorting on order property: grepcode.com/file/repo1.maven.org/maven2/org.thymeleaf/…Therefor
#39414555 - this article helped me.Peoria
F
0

A slight improvement of the previous answer:

@Configuration
public class ThymeleafConfig {

    public ThymeleafConfig(TemplateEngine templateEngine) {
        templateEngine.addTemplateResolver(new StringTemplateResolver());
    }
}
Fields answered 1/7, 2020 at 5:12 Comment(0)
N
0

In spring boot the Thymealeaf resolvers are autowired to the TemlpateEnging. You can do something very similar to @m4rtin answer with @Bean annotation:

@Configuration
public class ThymeleafExtension {

  @Bean
  public ITemplateResolver myFileTemlpateResolver() {
    FileTemplateResolver resolver = new FileTemplateResolver();
    resolver.setPrefix("D:\\templates\\");
    resolver.setSuffix(".html");
    resolver.setTemplateMode("HTML5");
    resolver.setOrder(templateEngine.getTemplateResolvers().size());
    resolver.setCacheable(false);
    return resolver;
  }
}
Nuptial answered 18/8 at 15:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.