Java 模板引擎 Thymeleaf(了解)

2017-07-08  本文已影响233人  司鑫

一 什么是 Thymeleaf


Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。和 JSP、FreeMaker 等类似,它也可以轻易的与 Spring MVC 等 Web 框架进行集成作为 Web 应用的模板引擎。

二 为什么要用 Thymeleaf


相对于其它的模板引擎,Thymeleaf 最大的优点就是前后端可以分离,能够直接在浏览器中打开并正确显示模板页面,方便美工的调试,而不需要启动整个Web应用。但在性能方面还需要有很大的提升空间。

三 使用


1、Thymeleaf 基本格式


<!DOCTYPE HTML>  
<html xmlns:th="http://www.thymeleaf.org">  
<head>  
    <title>Thymeleaf</title>  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />  
</head>  
<body>  
    
</body>  
</html>

注意:引入命名空间 <html xmlns:th="http://www.thymeleaf.org">

2、标准表达式

<span th:text="${user.name}"></span>
如果 user 对象中的 name 为 “acey”,那么就会被解析成
<span>acey</span>
<a th:href="@{http://www.thymeleaf.org}">Thymeleaf</a>
<a href="detail.html" 
   th:href="@{http://localhost:8080/user/detail(id=${id})}">view</a>
(id=${id}) 表示的是 URL 后面的参数被解析后就为 “?id=××”
<a href="detail.html" 
   th:href="@{http://localhost:8080/user/{id}/detail">view</a>
 {id} 访问的是 context 中的变量
<th th:text="#{prop.role">...</th> 

注:国际化资源一般是在.properties文件定义。

th:text="'id is' + ( (${id} == '1')? '1' : 'not 1')"

3、循环:th:each

<tr th:each="item : ${items}">
  <td th:text="${item.id}"></td>
</tr>

4、 条件

<a th:href="@{/login}" th:if=${user == null}>Login</a>
等于(unless 和 if 相反)
<a th:href="@{/login}" th:unless=${user != null}>Login</a>
<div th:switch="${user.role}">
  <p th:case="'admin'">admin</p>
  <p th:case="#{roles.manager}">manager</p>
 <p th:case="*">other</p>
</div>
'*'表示 default 
上一篇 下一篇

猜你喜欢

热点阅读