thymeleaf语法及使用

模板引擎

简介:模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。 模板引擎的思想: 在这里插入图片描述 Thymeleaf就是SpringBoot给我们推荐的一种模板引擎!

Thymeleaf模板引擎

1.使用Thymeleaf之前的步骤
  1. Thymeleaf 官网:https://www.thymeleaf.org/
  2. springboot项目直接引入依赖:
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

3.非springboot项目直接引入依赖:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>2.1.4</version>
</dependency>

4.在thymeleaf的配置类ThymeleafProperties中我们可以发现:thymeleaf配置的默认前缀为:"classpath:/templates/",默认后缀为:".html",只要把html页面放在这个路径下,

thymeleaf就可以帮我们自动渲染。

public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";
...
}

如图为用idea创建的springboot的项目结构:将html页面放在resources/templates中即可。 在这里插入图片描述

2.Thymeleaf语法简单使用(th:text, th:utext, th:each)

编写一个controller实现跳转到一个html页面,通过Model对象携带数据

@Controller
public class HelloController {

    @RequestMapping("/success")
    public String success(Model model){
        //存入数据
        model.addAttribute("msg","<h1>Hello</h1>");
        model.addAttribute("users", Arrays.asList("小红", "小米","小白"));
        //classpath:/templates/success.html
        return "success";
    }
}

success.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>success</h1>

    <!--Thymeleaf语法:th:text就是将div中的内容设置为它指定的值-->

    <div th:text="${msg}">你好</div>
    <!--utext:会解析html,显示相应的效果-->
    <div th:utext="${msg}">你好</div>
    <!--each:遍历-->
    <h3 th:each="user:${users}" th:text="${user}"></h3>

</body>
</html>

通过http://localhost:8080/success路径访问到success.html页面,同时成功显示数据:在这里插入图片描述

3.Thymeleaf基本语法(属性和表达式)

Thymeleaf标准表达式

  1. 变量表达式:${ }:用于前端获取后端传递的变量值

  2. 选择表达式:*{ }:用于绑定一个对象的属性

  3. URL链接表达式:@{ }:用于链接

  4. 条件表达式:三目运算符(表达式 ?值(then):值(else))

Thymeleaf属性标签: 在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值