Multiple Thymeleaf Template Locations with Spring Boot

This is one of those issues that on first glance would seem difficult, requiring perhaps a ServletContextTemplateResolver with a SpringTemplateEngine component, then a ThymeleafViewResolver piggy-backing off the TemplateEngine…or something similarly complicated. Instead we'll see how simple it is to have multiple Thymeleaf template locations by leveraging the built-in capabilities of Spring Boot.

First the setup. We've been talking about our new NixMash Blog app (on GitHub) which contains both private and public content. In our last post we covered how we're separating private and public content in Spring. Today we're using multiple Thymeleaf template locations to share content, or more specifically, to avoid duplicating content.

The Public Resources layout is below. /templates and /static are obvious, but we have two other directories. /common is for shared static resources: JavaScript libraries along with their CSS and other website staples we don't want to duplicate. /admin is our shared, um, ADMIN template directory. Regardless of the extent of application customizations made by developers in the Open Source release, we want only one administration template collection. So in other words, we need two Thymeleaf template areas.

The Code

That guy I described at the top of the post making this complicated was me. I wasn't leveraging what Spring Boot already brought to the table. Spring Boot has a ServletContextTemplateResolver built in, and a Template Engine, and when it sees Thymeleaf in the class path, Thymeleaf generates the View according to Spring's default configuration settings–unless we change them in or code.

Our job then is to chain two templateResolver components using the Thymeleaf ITemplateResolver Interface. Ignore the if (nixmashModeEnabled) and the /nixmash/ directory. That's from our earlier post on separating content. Our first templateResolver with setOrder(0) will use /templates/ while our adminTemplateResolver setOrder(1) will process templates in /admin/.

Here's a closer look at the Abstract classes of Thymeleaf's ITemplateResolver. As you see we're using SpringResourceTemplateResolver.

And there you have it, multiple Thymeleaf Template Locations with Spring Boot!

Source Code Notes for this Post

Source code discussed in this post can be found in my NixMash Blog project located on GitHub.

More Like This Post