Search code examples
spring-bootthymeleaf

Several template locations for Thymeleaf in Spring Boot


Currently Spring Boot allow one value for the Thymeleaf templates location with the spring.thymeleaf.prefix property.

The default value is classpath:/templates/.

I want to have another location for the thymeleaf templates (but keep the default one), outside the jar, for example:

spring.thymeleaf.prefix = classpath:/templates/, file:/resources/templates

Do i have to define another template resolver for the new location i want ?


Solution

  • Define the setting in the application.properties file

    spring.thymeleaf.templateResolverOrder=1 
    

    Now in your custom Bean which creates ITemplateResolver set order to 0 along with prefix and suffix. This way spring boot will listen to both places

    Setting order to 0 is important

    An example of bean creation can be

    @Bean
    public ClassLoaderTemplateResolver emailTemplateResolver() {
        ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
        emailTemplateResolver.setPrefix("mails/");
        emailTemplateResolver.setSuffix(".html");
        emailTemplateResolver.setTemplateMode(TemplateMode.HTML);
        emailTemplateResolver.setCharacterEncoding("UTF-8");
        emailTemplateResolver.setOrder(0);
        emailTemplateResolver.setCheckExistence(true);
    
        return emailTemplateResolver;
    }
    

    MyExample