Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 620
herau Avatar asked Mar 09 '17 11:03

herau


2 Answers

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

like image 142
rajadilipkolli Avatar answered Sep 23 '22 06:09

rajadilipkolli


In order to define multiple template locations, you must define Spring beans implementing ITemplateResolver.

@Bean
public SpringResourceTemplateResolver firstTemplateResolver() {
    SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
    templateResolver.setPrefix("classpath:/templates/templatelocation/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode(TemplateMode.HTML);
    templateResolver.setCharacterEncoding("UTF-8");
    templateResolver.setOrder(0);
    templateResolver.setCheckExistence(true);

    return templateResolver;
}

@Bean
public ClassLoaderTemplateResolver secondTemplateResolver() {
    ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
    templateResolver.setPrefix("templates/templatelocation/other/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode(TemplateMode.HTML);
    templateResolver.setCharacterEncoding("UTF-8");
    templateResolver.setOrder(1);
    templateResolver.setCheckExistence(true);

    return templateResolver;
}

You can also check out the blog post detailing the usage.

like image 44
injavawetrust Avatar answered Sep 23 '22 06:09

injavawetrust