史上最全SpringBoot教程,从零开始带你深入♂学习(五)——thymeleaf模板引擎

Springboot(五)——thymeleaf模板引擎

thymeleaf模板引擎

一、导入thymeleaf依赖或者在创建项目的时候勾选thymeleaf模板引擎

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

白嫖资料

二、根据源码,我们使用thymeleaf模板的时候,需要将html放在templates目录下

在templates目录下的所有页面,只能通过controller跳转!
并且需要模板引擎的支持!thymeleaf

private String prefix = "classpath:/templates/";
private String suffix = ".html";
private String mode = "HTML";

thymeleaf使用

一、编写controller

@RequestMapping("/test")
public String test(Model model){
    model.addAttribute("msg","hello,springboot");
    return "test";
}

二、在templates目录下新建test.html

<!DOCTYPE html>
<!--注:这里一定要引入头文件-->
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--th:text  取出的值被转义成text-->
<div th:text="${msg}"></div>
</body>
</html>

三、运行测试

白嫖资料


thymeleaf语法

一、controller编写

@RequestMapping("/test")
public String test(Model model){
    model.addAttribute("msg","<h1>hello,springboot</h1>");//加群1025684353一起吹水聊天
    model.addAttribute("users", Arrays.asList("zhangsan","lisi"));
    return "test";
}

二、html修改

白嫖资料

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--th:text  标注这个值是test-->
<div th:text="${msg}"></div>
<!--不转义-->
<div th:utext="${msg}"></div>
<hr>
<!--遍历集合-->
<h3 th:each=" user:${users}" th:text="${user}"></h3>
<!--遍历集合方式二:没有提示-->
<h3 th:each=" user:${users}" >[[${user}]]</h3>
<hr>
</body>
</html>

三、运行测试结果


白嫖资料

thymeleaf语法糖

基础语法

  • 普通变量:${}
  • 国际化消息:#{}
  • url链接@{}
  • 判断表达式~{}
  • 文本:'test'(单引号)

三元条件运算符

  • if-then:(if)?(then)
  • if-then-else:(if)?(then):(else)
  • Defult:(value)?:(defultvalue)

最后,祝大家早日学有所成,拿到满意offer,快速升职加薪,走上人生巅峰。 可以的话请给我一个三连支持一下我哟,我们下期再见

白嫖资料

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容