Thymeleaf——实战篇(一)

264 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

本文系作者 不太自律的程序猿原创,转载请私信并在文章开头附带作者和原文地址链接。

唠家常

之前也介绍过了Thymeleaf的一些语法使用,今天就来进入实战,例子也很简单,就是对于Thymeleaf中的th属性表达式的一些用法,以及实际开发可能会遇到的一些问题。废话不多说,开肝。

Thymeleaf实战

本次实战还是springboot集成Thymeleaf下去实现的。配置也比较简单,不做过多赘述,不清楚的可以查看之前的Thymeleaf——先导篇,里面有对环境的一些配置。如果有对th语法不熟悉的小伙伴,可以查看之前的Thymeleaf——语法篇中对于th属性表达式做了一些介绍,如果有不明白的,或者疑问,欢迎来评论去讨论。

th引入静态资源

th引入静态资源,可以实现公共部门资源的抽取,不必重复过多的代码,看上去会整洁不少。 th:fragment设置代码块名称,放入我们公共的资源,后续可以直接通过th:replace去引用。
定义

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="common_resource">
    <meta charset="UTF-8">
    
    <link rel="stylesheet" type="text/css" th:href="@{/layui/css/layui.css}"/>
    <script type="text/javascript" th:src="@{/js/jquery.js}"></script>
    <script type="text/javascript" th:src="@{/layui/layui.js}"></script>
    <script type="text/javascript" th:src="@{/js/util/core.util.js}"></script>

</div>

引用

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<div th:replace="common/common_resource :: common_resource"></div>
<heard>
<body>
</body>
</html>

继续在基础上进行扩展,之前只是简单的传递了一个变量的值,来在页面中显示,后续我们实际开发过程中会遇到好多需要去遍历数组的情况,所以添加了对th:each的使用,以及一些资源引入。

后端代码


@Controller 
@RequestMapping("/index") 
public class IndexController { 
@RequestMapping("/home") 
public String hello(Model model) { 

List<User> list = new ArrayList<>();
list.add(new User(5,"不太自律的程序猿5"));
list.add(new User(4,"不太自律的程序猿4"));
list.add(new User(3,"不太自律的程序猿3"));
list.add(new User(2,"不太自律的程序猿2"));
list.add(new User(1,"不太自律的程序猿1"));
model.addAttribute("userList", list);
model.addAttribute("msg", "不太自律的程序猿");

//值为1的话,页面就显示不太自律的程序猿1
//值为2的话,页面就显示不太自律的程序猿2
//传递其余值或者没有传值都显示case="*"对应的标签内容
model.addAttribute("flag", 3);

return "test";

} 
}

前端代码

<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org">
<head> <meta charset="UTF-8"> 
<title>不太自律的程序猿</title> 
</head> 
<body> 

<p>th:text</p>
<span th:text="${msg}">springboot集成thymeleaf</span> 

<p>th:each</p>
<div th:each="user:${userList}"> 
<span th:text="${user.id}"></span> 
<span th:text="${user.name}"></span> 
</div>

<p>th:switch</p>
<div th:switch="${flag}">
    <span th:case="1">不太自律的程序猿1</span><br/>
    <span th:case="2">不太自律的程序猿2</span><br/>
    <span th:case="*">不太自律的程序猿3</span>
</div>

</body> 
</html>

感谢诸君的观看,文中如有纰漏,欢迎在评论区来交流。如果这篇文章帮助到了你,欢迎点赞👍关注。