Create a custom "fragment resolver"

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

Create a custom "fragment resolver"

migueldeblas
I have this classpath:/templates/ for thymeleaf view. E.g.:
/parent1/index.html
/parent1/child1/
/parent1/child2/index.html

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 {

        @Override
        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 {

@Autowired
TemplateEngine templateEngine;

@Bean
public MyThymeleafViewResolver thymeleafViewResolver() {
   MyThymeleafViewResolver resolver = new MyThymeleafViewResolver();
   resolver.setTemplateEngine(templateEngine);
   (set config from spring boot  application.properties 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?

Thanks!
Loading...