Spring Boot学习笔记(四)——Thymeleaf

1.概述
在上篇笔记中我们学习了如何通过JPA对数据库进行操作,那接下来就是如何将数据显示到前台了,Spring Boot框架默认不支持JSP,这使得我们要使用HTML页面,为了完成页面动态化,Spring Boot很好的支持了模板引擎Thymeleaf。
2.目标
通过本次学习,能够完成在Spring Boot框架下Thymeleaf的配置与使用。
3.详细步骤

(1)配置
在pom.xml中添加依赖

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

在application.properties文件中添加配置项

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

(2)使用
要在HTML上使用Thymeleaf首先需要引入

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

语法
1.变量
${} 其作用是获取后台返回的变量值
th:text的作用是设置标签文本值

<p th:text="${user.name}"></p>

2.URL
@{} 其作用是用来获取URL对应的资源
th:href 用来设置资源地址

<link rel="stylesheet" th:href="@{css/bootstrap.css}"/>

3.字符串替换
这个基本上与变量一致不做过多赘述

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

这种是拼接字符串的形式,还有另一个更简单的形式

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

4.运算符
在表达式中可以使用各类算术运算符,例如+, -, *, /, %,以及各种逻辑运算符>, <, <=,>=,==,!=,其中<,>要是用html转义符

th:if="${count} &lt; 1"
th:if="${count} &gt; 1"

5.for循环
th:each的使用

<div  th:each="user:${list}"  class="col-sm-6 col-sm-offset-2" style="margin-bottom: 10px">
    <span th:text="${user.name}"></span>
</div>

6.if/unless
th:if的标签表达式结果为真就显示这部分标签,否则不显示;th:unless与th;if相反结果为真就不显示,结果为假就显示


      <div class="col-md-2"  th:title="${url.description}" th:if="${lstat.index}%4 == 0" >
           <strong th:text="${url.link_name}">这个冬天不太冷</strong>
       </div>

       <div class="col-md-2 col-md-offset-1" th:title="${url.description}" th:unless="${lstat.index}%4==0">
           <strong th:text="${url.link_name}">这个冬天不太冷</strong>
       </div>

7.switch
th:switch与th:case搭配使用,*代表default,其使用基本与java语言使用无异

<div th:switch="${role}">
  <p th:case="'admin'">admin</p>
  <p th:case="'manager'">manager</p>
  <p th:case="*">default</p>
</div>

8.th:onclick
其作用是当触发点击事件时,运行表达式

 <li id="more" style="width: 100%;display: inline-table" th:onclick="showMoreAttented(page++)" >
                <a style="width: 100%;display: inline-table">更多关注</a>
 </li>

9.session
可以通过session对象,直接访问session中的attribution获取值

 <p class="text-center" th:text="${session.user.name}"></p>

10.fragment与include
可以通过fragment与include完成前端页面模板的引用

定义模板

<div th:fragment="nav"  xmlns:th="http://www.w3.org/1999/xhtml">
    •••此处省略
</div>

使用模板

<div th:include="nav :: nav"></div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值