Search code examples
javaspring-mvcspring-bootthymeleaf

What is TemplateResolver.setOrder user for in thymleaf?


I am using Thymeleaf for my email templates and I was googling and was able to run the code successfully with the following config:-

@Configuration
public class TemplateEngineConfig {

    @Autowired
    private MailConfigProps mailConfigProps;

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.addTemplateResolver(templateResolver());
        return templateEngine;
    }

    private TemplateResolver templateResolver() {
        TemplateResolver resolver = new ClassLoaderTemplateResolver();
        resolver.setPrefix(mailConfigProps.getTemplatePath());
        resolver.setSuffix(".html");
        resolver.setTemplateMode("HTML5");
        resolver.setOrder(1);
        resolver.setCacheable(true);
        return resolver;
    }
}

Everything here is understandable to me except setOrder. I tried looking up for it in different places and the only info that I get is that " Sets a new order for the template engine in the chain. The order should start with 1.".

Below is what documentations says:

setOrder
public void setOrder(Integer order)
Sets a new order for the template engine in the chain. Order should start with 1.
Parameters:
order - the new order.
Can someone please share why `setOrder` is there and when should it be used in my application and what should be the appropriate values to be set in different scenarios.

What happens if I don't provide this value?


Solution

  • Your application may use different types of Templates like HTML, TXT or String etc.Those may have multiple types of template resolvers. Those multiple template resolver can be registered with the template engine. All the view resolvers in the application executing in the ordered chain until one of them are able to resolve that view.So, TemplateResolver#setOrder basically decide the order of the chain. There is a resolvablePatterns property which is the one to determine whether a template resolver will consider a view name to be resolved by it or not. You can also set the resolvablePatterns by setResolvablePatterns

    templateResolver.setResolvablePatterns(Collections.singleton("text/*"));