Search code examples
springtemplatesthymeleaf

Thymeleaf templates in class package


Is there a way to store Thymeleaf templates not in resources or webapp, but in the same packages as classes instead? For example structure like this:

com
   example
      myapp
         foo
            Foo.class
            Template.html
         bar
            Bar.class
            Template.html
            OtherTemplate.html

How would I have to configure Spring and Thymeleaf in order to achieve this?


Solution

  • You need to define a ClassLoaderTemplateResolver in the WebMvcConfigurer.

    In the following example, the base package where I have my templates is net.yadaframework.views (which whould be com.example.myapp in your case). When I return a view from a Controller, the path is relative to that package, so "/foo/Template" in your example. The patterns Set should contain the subfolders of the base package, so "/foo/*" and "/bar/*" in your example.

    @EnableWebMvc
    @ComponentScan(basePackages = { "net.yadaframework.views" })
    public class YadaWebConfig implements WebMvcConfigurer {
    
        public ClassLoaderTemplateResolver yadaTemplateResolver() {
            ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
            resolver.setPrefix("net/yadaframework/views");
            /* From the tutorial:
             When several template resolvers are applied, it is recommended to specify patterns 
             for each template resolver so that Thymeleaf can quickly discard those template resolvers 
             that are not meant to resolve the template, enhancing performance. Doing this is not a 
             requirement, but a recommendation
             */
            Set<String> patterns = new HashSet<>();
            patterns.add("/yada/*"); // Start with "yada". Patterns are NOT regexp
            patterns.add("/yadacms/*"); // Start with "yadacms". Patterns are NOT regexp
            resolver.setResolvablePatterns(patterns);
            resolver.setSuffix(".html");
            resolver.setCharacterEncoding("UTF-8");
            resolver.setTemplateMode(TemplateMode.HTML);
            resolver.setCacheable(true);
            resolver.setOrder(10); 
            return resolver;
        }