一. 什么是Thymeleaf

Thymeleaf是面向Web和独立环境的现代服务器端Java模板引擎。
Thymeleaf的主要目标是为您的开发工作流程带来优雅的自然模板 - 可以正确显示在浏览器中的HTML,也可以作为静态原型工作,从而在开发团队中进行更强大的协作。
随着Spring框架的模块,与您最喜欢的工具的集成,以及插入自己的功能的能力,Thymeleaf是现代HTML5 JVM Web开发的理想选择,尽管它可以做的更多。

好吧,我承认刚才那段是Thymeleaf官方的说明,我只不过机翻了一下。下面咱们说点人话。Thymeleaf就是jsp的高端升级版。

二. 什么情况适合使用Thymeleaf

Thymeleaf显然是一个开发页面的技术,现在各种前端技术层出不穷,比如现在主流的Vue、React、AngularJS等。很多人可能会要问,这个Thymeleaf相对于这些前端框架到底有啥优势。
其实,Thymeleaf跟那些前端框架根本不是一个类型的东西,也没有啥可比性。

Thymeleaf和老牌的jsp属于非前后分离的思路来开发的。后端通过数据渲染html的模板,渲染后模板就是个完整的html页面,将页面返回给请求方。

主流的前端框架是基于前后端分离的思路来开发的,前端页面通过ajax来调用后端的rest接口来获取数据,再通过js进行渲染页面(不管什么前端技术其实都是对js进行了封装,js依然是底层核心)。

下面看下springboot配合Thymeleaf完美实现遍历功能,内容详情如下所示:

1:控制层代码,写一个数组集合

2:视图层:写th:each这里类似于vue语法

结果展示:

源码:控制层

package com.example.demo.controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Arrays;


/**
 * @author ${范涛之}
 * @Description
 * @create 2021-09-11 20:31
 * 自动装配
 * 本身就是spring的组件
 */
@Controller
public class HelloController {
    @GetMapping("/test")
    public  String test(Model model){
        model.addAttribute("msg","<h1>helloftzdsj</h1>");


        model.addAttribute("users", Arrays.asList("fantaozhi","dengsijia"));

        return "index";
    }


}

源码:视图层

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div th:text="${msg}"></div>
<div th:utext="${msg}"></div>   //转意

<hr>
<h3 th:each="user:${users}"  th:text="${user}"></h3>
</body>
</html>

同样可以在视图层这样写:
使用中括号(但是不建议)

<h3 th:each="user:${users}"> [[${user}]]</h3>

实现了同样的效果

到此这篇关于springboot配合Thymeleaf完美实现遍历的文章就介绍到这了,更多相关springboot Thymeleaf遍历内容请搜索悠悠之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠悠之家!

点赞(93)

评论列表共有 0 条评论

立即
投稿
返回
顶部