官术网_书友最值得收藏!

Configuring a Thymeleaf template engine

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.

主站蜘蛛池模板: 东辽县| 浮梁县| 镇康县| 玉门市| 馆陶县| 通道| 景东| 平舆县| 曲阳县| 广南县| 灵寿县| 华容县| 讷河市| 华池县| 牙克石市| 平塘县| 余姚市| 长顺县| 富蕴县| 宿松县| 罗甸县| 庄河市| 泰和县| 成武县| 茶陵县| 邳州市| 博爱县| 偃师市| 竹山县| 兴和县| 新闻| 临洮县| 夏邑县| 邯郸市| 富源县| 怀宁县| 商南县| 合阳县| 梓潼县| 南阳市| 西畴县|