We will be using the Thymeleaf template engine for handling server-side templates. Thymeleaf provides various dialects and conditional blocks for rendering the dynamic content within the static HTML. Let's look at some simple syntactical element of Thymeleaf, as follows:
<!-- Dynamic content in HTML tag --> <div class="alert alert-info">[[${country.name}]]</div> <!-- Dynamic attributes --> <span th:class="|alert ${error ? 'alert-danger': _}|">[[${errorMsg}]]</span> <!-- Looping --> <ol> <li th:each="c : ${countries}"> [[${c.name}]] </li> </ol> <!-- Conditionals --> <div class="alert alert-warning" th:if="${count == 0}">No results found</div> <!-- Custom attributes --> <div th:attr="data-count=${count}"></div> <!-- Form element value --> <input type="text" th:value="${country.name}" name="name" />
From the previous examples, we can observe that the items to be evaluated by Thymeleaf are prefixed with th:
and any content to be rendered between the tags can be done either using th:text
or [[${variable}]]
. The latter syntax has been introduced in Thymeleaf 3. This was a very short primer, as going in to depth on Thymeleaf is out of the scope of this book. A beautiful guide explaining different parts of the template can be found at http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html.
In order to use the Thymeleaf template engine with Spring MVC, we need to do some configuration wherein we set up the Thymeleaf template engine and update Spring's view resolver to use the template engine to resolve any views. Before moving further, we need to define required dependencies in pom.xml
as follows:
<dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>${thymeleaf.version}</version> </dependency> <dependency> <groupId>nz.net.ultraq.thymeleaf</groupId> <artifactId>thymeleaf-layout-dialect</artifactId> <version>${thymeleaf-layout-dialect.version}</version> </dependency>
Let's define the configuration view resolver in order, starting with setting up the template resolver as follows:
@Bean public ClassLoaderTemplateResolver templateResolver() { ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); templateResolver.setPrefix("templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode(TemplateMode.HTML); templateResolver.setCacheable(false); return templateResolver; }
The previous configuration sets the template location that the template engine will use to resolve the template files. Next is to define the template engine, which will make use of SpringTemplateEngine
and the template resolver defined earlier, as follows:
@Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); templateEngine.addDialect(new LayoutDialect()); return templateEngine; }
In the previous configuration, we make use of the Thymeleaf Layout Dialect (https://github.com/ultraq/thymeleaf-layout-dialect) created by Emanuel Rabina. This layout dialect helps us in creating a view decorator framework wherein all the templates will be decorated with a base template and the decorated templates just provide the necessary content to complete the page. So all the headers, footers, CSS, scripts, and other common HTML can be placed in the base template. This prevents redundancy to a great extent. In our sample app, the base.html
file present in worldgdp/src/main/resources/templates
is the base template that is used by other templates.
Next is to define a Thymeleaf view resolver that will override Spring's default view resolver, as follows:
@Bean public ViewResolver viewResolver() { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); viewResolver.setCharacterEncoding("UTF-8"); return viewResolver; }
The previous configuration is available in the com.packt.config.ViewConfiguration
class.
If you look back at the com.nilangpatel.worldgdp.AppConfiguration
class, you will see that we have overridden the addResourceHandlers
method of WebMvcConfigurer
interface. In the method implementation shown in the following code, we have mapped the static resources prefix URL /static/**
to the static resources location /static/
in the webapp
directory:
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**") .addResourceLocations("/static/"); }
We mentioned before that we will be using the Thymeleaf Layout Dialect to create a base template and use the base template to decorate all other templates. The base template will contain all the CSS links, JavaScript source file links, the header, and the footer, as shown in the following code:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"> <head> <title layout:title-pattern="$CONTENT_TITLE - $LAYOUT_TITLE">World In Numbers</title> <meta name="description" content=""/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <!-- Include all the CSS links --> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-primary"> <a class="navbar-brand" href="#">WORLD IN NUMBERS</a> <div class="collapse navbar-collapse" id="navbarColor01"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" th:href="@{/countries}">Countries</a> </li> </ul> </div> </nav> <div class="container"> <div class="content"> <div layout:fragment="page_content"> <!-- Placeholder for content --> </div> </div> </div> <div class="modal" id="worldModal" > </div> <footer id="footer"></footer> <!-- /.container --> <!-- Include all the Javascript source files --> <th:block layout:fragment="scripts"> <!-- Placeholder for page related javascript --> </th:block> </body> </html>
The two main important parts of the following template are as follows:
<div layout:fragment="page_content"></div>
: The other templates that use the base template as decorator provide their HTML within this section. Thymeleaf Layout Dialect at runtime decorates this HTML with the content from the base template.<th:block layout:fragment="scripts"></th:block>
: Similar to the HTML previous content, any page-specific JavaScript or links to any specific JavaScript source files can be added within this section. This helps in isolating page-specific JavaScript in their own pages.
Any template that wants to use the base template as the decorator will declare this attribute, layout:decorate="~{base}"
, in the <html>
tag. We will not go into the content of individual templates as it's mostly HTML. All the templates can be found at the location worldgdp/src/main/resources/templates
. We have three templates:
countries.html
: This is for showing the countries' list with filtering and paginationcountry-form.html
: This is for editing a country's detailcountry.html
: This is for showing a country's detail