zoukankan      html  css  js  c++  java
  • SpringBoot之模板引擎

    一、Thymeleaf

    1.1 集成 templates

    pom.xml 文件中添加依赖

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

    application.yml 文件中添加配置

    spring:
      thymeleaf:
        # 模板文件前缀
        prefix: classpath:/templates/
        # 模板文件后缀
        suffix: .html
    

    ​ 注:这些属性是 ThymeleafProperties 默认的配置,如果不需要变更的话可以不用配置。

    1.2 实例

    java目录下新建 HelloController.java 文件

    @Controller
    public class HelloController {
    
        @RequestMapping("/hello")
        public String hello(Model model) {
            // 普通文本
            model.addAttribute("text","MarkLogZhu");
            // 普通类型数组
            int[] array = new int []{10,2,33,4,5};
            model.addAttribute("array", array);
            // 对象列表
            List<User> users = new ArrayList<>();
            users.add(new User(1,"张三"));
            users.add(new User(2,"李四"));
            users.add(new User(3,"王五"));
            model.addAttribute("users", users);
            return "hello";
        }
        
    }
    

    templates 目录下新建 hello.html 文件

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>SpringBoot-thymeleaf demo</title>
    </head>
    <body>
    <p th:text="'hello, ' + ${text} + '!'"/>
    
    <table>
        <tr th:each=" arr : ${array}">
            <td th:text="${arr}">序号</td>
        </tr>
    </table>
    
    
    <table>
        <thead>
        <th>序号</th>
        <th>用户 id</th>
        <th>用户名</th>
        </thead>
        <tbody>
        <tr th:each=" user,userStat : ${users}">
            <td th:text="${userStat.index+1}">序号</td>
            <td th:text="${user.userId}">用户 id</td>
            <td th:text="${user.userName}">用户名</td>
        </tr>
        </tbody>
    </table>
    
    
    </body>
    </html>
    

    启动项目,在浏览器访问:http://localhost:8080/hello

    1.3 常用语法

    关键字 功能介绍
    th:id 替换id
    th:text 文本替换
    th:utext 支持html的文本替换
    th:object 替换对象
    th:value 属性赋值
    th:with 变量赋值运算
    th:style 设置样式
    th:onclick 点击事件
    th:each 属性赋值
    th:if 判断条件
    th:unless 和th:if判断相反
    th:href 链接地址
    th:switch 多路选择 配合th:case 使用
    th:case th:switch的一个分支
    th:fragment 布局标签,定义一个代码片段,方便其它地方引用
    th:include 布局标签,替换内容到引入的文件
    th:replace 布局标签,替换整个标签到引入的文件
    th:selected selected选择框 选中
    th:src 图片类地址引入
    th:inline 定义js脚本可以使用变量
    th:action 表单提交的地址
    th:remove 删除某个属性
    th:attr 设置标签属性,多个属性可以用逗号分隔

    更多语法请参考 thymeleaf 官方文档

  • 相关阅读:
    2011年9月11日的最后几分钟开始学习Zend freamework
    PHP常用的调试技术 一周的时间正在整理
    二叉树最近共同祖先问题
    最近一段时间的思考
    字符编码笔记:ASCII,Unicode和UTF8
    node简介
    如何影响别人
    HTTP协议状态码详解(HTTP Status Code)
    jQuery常见的50种用法
    php上传多张图片
  • 原文地址:https://www.cnblogs.com/markLogZhu/p/11776505.html
Copyright © 2011-2022 走看看