Java模板引擎Thymeleaf

简介:1)thymeleaf是一种基于html的模板语言,类似于freemark等

          2)总体为了代替jsp,实现前后端分离

          3)官方文档:https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#appendix-b-expression-utility-objects

1、变量(today数据放置于controller层model对象中)

Thymeleaf模板引擎在进行模板渲染时,还会附带一个Context存放进行模板渲染的变量,在模板中定义的表达式本质上就是从Context中获取对应的变量的值:

<p>Today is: <span th:text="${today}">13 february 2011</span>.</p>

假设today的值为2015年8月14日,那么渲染结果为:<p>Today is: 2015年8月14日.</p>。可见Thymeleaf的基本变量和JSP一样,都使用${.}表示获取变量的值

2、URL

URL在Web应用模板中占据着十分重要的地位,需要特别注意的是Thymeleaf对于URL的处理是通过语法@{...}来处理的。Thymeleaf支持绝对路径URL:

<a th:href="@{http://www.thymeleaf.org}">Thymeleaf</a>

同时也能够支持相对路径URL:

  • 当前页面相对路径URL——user/login.html,通常不推荐这样写。
  • Context相关URL——/static/css/style.css

另外,如果需要Thymeleaf对URL进行渲染,那么务必使用th:hrefth:src等属性

3、字符串替换

很多时候可能我们只需要对一大段文字中的某一处地方进行替换,可以通过字符串拼接操作完成:

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

一种更简洁的方式是:

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

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

4、运算符

在表达式中可以使用各类算术运算符,例如+, -, *, /, %

th:with="isEven=(${prodStat.count} % 2 == 0)"

逻辑运算符><<=,>===,!=都可以使用,唯一需要注意的是使用<,>时需要用它的HTML转义符:

th:if="${prodStat.count} &gt; 1"
th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"

5、循环

渲染列表数据是一种非常常见的场景,例如现在有n条记录需要渲染成一个表格<table>,该数据集合必须是可以遍历的,使用th:each标签:

<body>
  <h1>Product list</h1>

  <table>
    <tr>
      <th>NAME</th>
      <th>PRICE</th>
      <th>IN STOCK</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>

  <p>
    <a href="../home.html" th:href="@{/}">Return to home</a>
  </p>
</body>

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

6、条件求值

6.1、

If/Unless

Thymeleaf中使用th:ifth:unless属性进行条件判断,下面的例子中,<a>标签只有在th:if中条件成立时才显示:

<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

th:unlessth:if恰好相反,只有表达式中的条件不成立,才会显示其内容。

6.2、Switch

Thymeleaf同样支持多路选择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>
</div>

默认属性default可以用*表示:

<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>

6.3、补充(引入js/css文件)

<script th:src="@{/product/layui/layui.js}"></script>
<link th:href="@{/common/css/example/module.css}" rel="stylesheet"/>

6.4、连接后添加自定义数字

<!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->

<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>

6.5 js中获取controller层model中传递的值

<script>
    var bid = "[[${bid}]]";
<script>

6.6、常用参数

Java模板引擎Thymeleaf