码迷,mamicode.com
首页 > 其他好文 > 详细

Thymeleaf 2.0 --- 入门简介

时间:2015-03-20 14:36:39      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:thymeleaf 模板技术 template

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小节的表,th标记

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

本文出自 “Yan” 博客,请务必保留此出处http://jiaoyan.blog.51cto.com/8781601/1622522

Thymeleaf 2.0 --- 入门简介

标签:thymeleaf 模板技术 template

原文地址:http://jiaoyan.blog.51cto.com/8781601/1622522

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!