zoukankan      html  css  js  c++  java
  • Thymeleaf快速入门

    1.什么是Thymeleaf

    • Thymeleaf是用来开发Web和独立环境项目的服务器端的Java模版引擎

    • Spring官方支持的服务的渲染模板中,并不包含jsp。而是Thymeleaf和Freemarker等,而Thymeleaf与SpringMVC的视图技术,及SpringBoot的自动化配置集成非常完美,几乎没有任何成本,你只用关注Thymeleaf的语法即可。

    2.Thymeleaf的特点

    • 动静结合:Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

    • 开箱即用:它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

    • 多方言支持:Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

    • 与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器,我们可以像以前操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区别。

    3.springboot整合Thymeleaf

    3.1 安装依赖

    创建一个springboot项目,在pom.xml里面配置如下依赖

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

    3.2 简单使用Thymeleaf

    创建一个controller,用于给页面传递数据

    @Controller
    public class HelloController {
    
        @GetMapping("/hello")
        public String test(Model model){
            model.addAttribute("title","传递的数据");
            return "index";
        }
    }

    创建HTML文件,用Thymeleaf模板

    <!DOCTYPE html>
    <html lang="ch" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title th:text="${title}">首页</title>
    </head>
    <body>
    <h1>我是首页</h1>
    <a href="../hello">我是a标签请点我</a>
    </body>
    </html>

    当我们运行项目访问接口的时候,title就会被替换

    4.Thymeleaf常用方法

    (1) 替换文本

    th:text=${title} 

    (2)渲染返回对象里面的值

    <div th:object="${user}">
      <p th:text="*{age}"></p>
    </div>

    (3)判断是否渲染

    <p th:if="${user.isVip}">会员</p>

    (4)循环渲染

    <li th:each="tag:${user.tags}" th:text="${tag}">
    </li>

    (5)选择渲染

    <div th:switch="${user.sex}">
        <p th:case="1">男</p>
        <p th:case="2">女</p>
        <p th:case="*">默认</p>
    </div>

    (6)动态渲染

    <script th:inline="javascript">
    const user = /*[[${user}]]*/{};
    </script>

    (7)追加class

    th:classappend="active"

    5.Thymeleaf组件的使用

    5.1 定义组件

    <div th:fragment="com1">
        com1
    </div>
    <div th:fragment="com2">
        com2
    </div>
    ....

    5.2 使用组件

    替换标签

    <div th:replace="~{component::com1}"></div>

    添加标签

    <div th:insert="~{component::com1}"></div>

    一点点学习,一丝丝进步。不懈怠,才不会被时代所淘汰!

  • 相关阅读:
    ASPxGridView之ASPxGridViewExporter
    Asp.net中,从弹出窗体取选择值
    ASPxGridView中常用操作
    asp.net Webconfig
    白皮书 CPU卡基本知识
    Linux 中的计时 转自IBM china
    网络无缝融合技术(转)
    UMA相关的网站
    几本不错的书
    手机基带芯片供应商严阵以待,备战3G市场
  • 原文地址:https://www.cnblogs.com/fqh2020/p/14789215.html
Copyright © 2011-2022 走看看