Spring Boot+Thymeleaf学习

添加Thymeleaf依赖

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

Spring Boot默认存放模板页面的路径在src/main/resources/templates

<html>标签中引入:

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

条件语句 th:if

 <li th:if="${session.user != null}">
	<a href="/publish">发布</a>
</li>

迭代器 th:each

遍历questions集合

<div class="media" th:each="question:${questions}">
	...
</div>

图片地址 th:src

<a href="#">
	<img class="media-object img-circle"
			th:src="${question.user.avatarUrl}">
</a>

文本显示 th:text

<span th:text="${#dates.format(question.gmtCreate,'yyyy.MM.dd')}"></span>
<!-- #dates.format 定义时间格式,question.gmtCreate是定义的时间,右边的是格式 例:yyyy是2019,MM是09,dd是23-->

页面回显 th:value

<div class="form-group">
	<label for="title">问题标题(简单扼要):</label>
	<input type="text" class="form-control" th:value="${title}" id="title" name="title" placeholder="问题标题...">
</div>

部分后台代码

@PostMapping("/publish")
    public String doPublish(
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "description", required = false) String description,
            @RequestParam(value = "tag", required = false) String tag,
            HttpServletRequest request,
            Model model) {
            	...
            }

<textarea>标签里的回显问题:要用th:text才起作用,th:value不起作用 不懂为什么??


设置样式 th:class

<li th:class="${pagination.page==page}? 'active' : ''">
	...
</li>
<!--三目运算符,条件成立时,设置class为active,否则设置为空-->

链接拼接 th:href

<a  th:href="@{/(page=${page})}" th:text="${page}"></a>
<!--@{} ${} -->
 <a th:href="@{'/profile/'+${section}(page=${2})}" aria-label="Previous">
	...
</a>
<!-- 例如要拼接这样的地址:~/profile/questions?page=2  -->

引用片段 th:insert

/templates目录下新建一个名为navigation.html的文件,内容是:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
	<body>
	
    	<div th:fragment="nav">
    		<!-- 放入要被引用的片段 —— 类似多个页面都是相同的代码这种 -->
    		...
		</div>
		
	</body>
</html>

使用(在页面中引入)

<body>
  ...
  <div th:insert="~{navigation:: nav}"></div>
  <!--navigation是用来装片段的文件名称,nav是片段名-->
</body>

以上是做项目过程中用到的部分Thymeleaf知识点

参考资料——thymeleaf官网

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值