Thymeleaf 入门

引用
http://www.cnblogs.com/jiangbei/p/8462294.html
https://blog.csdn.net/u012706811/article/details/52185345
http://blog.didispace.com/springbootweb/

接触项目看到在html中有,

<span class="user_info" th:text="${user.name}"></span>

产生疑惑 所知道html为静态页面,这个显然为一个获取变量的表达式。在网上查询到为一个支持html的模板引擎。感觉很强大和方便,相当于代替了jsp的一些功能。从上面的文章借鉴整理一下 留着用。

## 1.引入依赖

springboot直接引入:

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

非springboot项目使用如下依赖:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>2.1.4</version>
</dependency>

可以查看依赖关系,发现spring-boot-starter-thymeleaf下面已经包括了spring-boot-starter-web,所以可以把spring-boot-starter-web的依赖去掉.

2.配置视图解析器

spring-boot很多配置都有默认配置,比如默认页面映射路径为
classpath:/templates/*.html
同样静态文件路径为
classpath:/static/

在application.properties中可以配置thymeleaf模板解析器属性

#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false

3.举例

@Controller
    public class HelloController {

        private Logger logger = LoggerFactory.getLogger(HelloController.class);
        /**
         * 测试hello
         * @return
         */
        @RequestMapping(value = "/hello",method = RequestMethod.GET)
        public String hello(Model model) {
            model.addAttribute("name", "Dear");
            return "hello";
        }

    }
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<!--/*@thymesVar id="name" type="java.lang.String"*/-->
<p th:text="'Hello!, ' + ${name} + '!'" >3333</p>
</body>
</html>
注释为IDEAALT+enter)生成的索引,便于IDEA补全

4.基础语法

首先要在改写html标签

<html xmlns:th="http://www.thymeleaf.org">

1.获取变量值
获取变量值用$符号,对于javaBean的话使用变量名.属性名方式获取,这点和EL表达式一样.

另外$表达式只能写在th标签内部,不然不会生效
2.引入URL
Thymeleaf对于URL的处理是通过语法@{…}来处理的

<a th:href="@{http://blog.csdn.net/u012706811}">绝对路径</a>
<a th:href="@{/}">相对路径</a>
<a th:href="@{css/bootstrap.min.css}">Content路径,默认访问static下的css文件夹</a>
类似的标签有:th:href和th:src

3.字符串替换

<span th:text="'Welcome to our application, ' + ${user.name} + '!'">

一种更简洁的方式是:

<span th:text="|Welcome to our application, ${user.name}!|">

当然这种形式限制比较多,|…|中只能包含变量表达式${…},不能包含其他常量、条件表达式等。
4.运算符
数学运算

二元操作:+, - , * , / , %
一元操作: - (负)
    逻辑运算

一元 : and or
二元 : !,not
    比较运算(为避免转义尴尬,可以使用括号中的英文进行比较运算!)

比较:> , < , >= , <= ( gt , lt , ge , le )
等于:== , != ( eq , ne )
    条件运算

If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)

'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

5.条件
if/unless
Thymeleaf中使用th:if和th:unless属性进行条件判断,下面的例子中,标签只有在th:if中条件成立时才显示:
th:unless于th:if恰好相反,只有表达式中的条件不成立,才会显示其内容。

	th:if="${prodStat.count} > 1"
    th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"
<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

switch

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>
默认属性default可以用*表示:

6.循环
通过th:each

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
    <!-- 不存在则忽略,显示hello null!(可以通过默认值进行设置)-->
    <p th:text="'Hello ' + (${name}?:'admin')">3333</p>
    <table>
        <tr>
            <th>ID</th>
            <th>NAME</th>
            <th>AGE</th>
        </tr>
        <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>
    </table>
</body>
</html>

以看到,需要在被循环渲染的元素(这里是)中加入th:each标签,其中th:each=”prod : ${prods}”意味着对集合变量prods进行遍历,循环变量是prod在循环体中可以通过表达式访问。

7.Utilities
为了模板更加易用,Thymeleaf还提供了一系列Utility对象(内置于Context中),可以通过#直接访问:
不推荐 前端以减少逻辑为主。
详情见https://blog.csdn.net/u012706811/article/details/52185345

Thymeleaf 入门
表单参数绑定还是很有用的!使用与注意事项,参见
https://blog.csdn.net/huihuilovei/article/details/64466548
Thymeleaf 常用属性
https://www.cnblogs.com/hjwublog/p/5051732.html

相关文章: