Create a custom "fragment resolver"

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

Create a custom "fragment resolver"

I have this classpath:/templates/ for thymeleaf view. E.g.:

I create a class to get a view from parent folder if a view doesn't exists:
If it tries to get this view /parent1/child1/index.html and if exists ok, but if doesn't exist it tries to get /parent1/index.html.

The pseudocode of this class that:

public class MyThymeleafViewResolver extends ThymeleafViewResolver {

        public View resolveViewName(String viewName, Locale locale) throws Exception {

        if (resource(viewName).exists())
                return super.resolverViewName(viewName);
         else {
                parentViewName = functionThatGetParentDirectory(viewName);
                return super.resolverViewName(parentViewName);

And my WebMvcConfig:

public class WebMvcConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {

TemplateEngine templateEngine;

public MyThymeleafViewResolver thymeleafViewResolver() {
   MyThymeleafViewResolver resolver = new MyThymeleafViewResolver();
   (set config from spring boot thymeleaf.* =)
   return resolver;

Surprisingly it works with view and fragment from controller!
But when I use <th:replace> if a fragment doesn't exist, it doesn't try to get from parent folder and it throws a exception.

What class/es and method/s should I inherit/override to reproduce the same search process in th:replace fragments?