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

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.

主站蜘蛛池模板: 米泉市| 育儿| 和顺县| 仲巴县| 东安县| 阿拉善盟| 长治市| 绍兴县| 临汾市| 南川市| 洛川县| 苏尼特左旗| 柳林县| 莱阳市| 宁南县| 昌图县| 中牟县| 饶平县| 安新县| 南康市| 宝兴县| 康乐县| 宝兴县| 翁源县| 汕尾市| 中方县| 巩义市| 沂南县| 邵武市| 仙居县| 瓦房店市| 武安市| 海林市| 宝丰县| 浏阳市| 防城港市| 江口县| 赤峰市| 青神县| 平邑县| 同德县|