Thymeleaf入门介绍

来源:互联网 发布:音频矩阵品牌 编辑:程序博客网 时间:2024/05/22 06:37

Thymeleaf,众多模板中的一员。因为项目使用的Spring Boot,而thymeleaf是它的内置集成的模板引擎,使用了一下。简单易学,上手快。文档例子都很易读,够用了!

安装

在Spring Boot项目中加入依赖,编译。配置文件如下

Maven

<dependencies>     <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId>     </dependency> </dependencies>

Gradle

dependencies {     compile("org.springframework.boot:spring-boot-starter-thymeleaf") }

模板文件位置

默认情况下我们需要把编写的模板文件放在src/main/resources/templates目录下,如图

templates下面可以按工程需要建立子目录,例如图中的components子目录。

如果想要更换templates目录可以修改spring.thymeleaf.prefix配置项.参见后面的配置项。

还想了解更多引擎配置的知识,请参见

Themeleaf配置项

在application.properties里可以对Thymeleaf进行相关配置

# THYMELEAF (ThymeleafAutoConfiguration) spring.thymeleaf.check-template-location=true spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.excluded-view-names= # comma-separated list of view names that should be excluded from resolution spring.thymeleaf.view-names= # comma-separated list of view names that can be resolved spring.thymeleaf.suffix=.htmlspring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html # ;charset=<encoding> is added spring.thymeleaf.cache=true # set to false for hot refresh

标准表达式语法

模板技术主要功能就是根据逻辑将后台模型中的对象与HTML结合,生成最终页面。标准表达式语法处理java对象在HTML中的结合问题。

文字

<p>   Now you are looking at a <span th:text="'working web application'">template file</span>. </p>

URL

使用绝对路径,,

<ol>   <li><a href="product/list.html" th:href="@{/product/list}">Product List</a></li>   <li><a href="order/list.html" th:href="@{/order/list}">Order List</a></li> </ol>

条件表达式

<tr th:class="${row.even}? 'even' : 'odd'">   ... </tr>

遍历

遍历prods集合,打印每个prod对象的属性

<tr th:each="prod : ${prods}">     <td th:text="${prod.name}">Onions</td>     <td th:text="${prod.price}">2.41</td>     <td th:text="${prod.inStock}? #{true} : #{false}">yes</td> </tr>

th:XX语法的支持请参考官方文档5.2小节的表,

更多的标记语法可以查看官方文档,例子说明都很详实。

0 0