• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

SpringBoot引入Thymeleaf的实现方法

springboot 搞代码 4年前 (2022-01-05) 30次浏览 已收录 0个评论

这篇文章主要介绍了SpringBoot引入Thymeleaf的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1.Thymeleaf简介

Thymeleaf是个XML/XHTML/HTML5模板引擎,可以用于Web与非Web应用 

Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模,Thymeleaf的可扩展性也非常棒。你可以使用它定义自己的模板属性集合,这样就可以计算自定义表达式并使用自定义逻辑,Thymeleaf还可以作为模板引擎框架。

2.引入Thymeleaf

引入依赖

在maven(pom.xml)中直接引入:

  org.springframework.bootspring-boot-starter-thymeleaf org.springframework.bootspring-boot-starter-web

配置Thymeleaf

在application.yml配置Thymeleaf

 server: port: 8000 spring: thymeleaf: cache: false # 关闭页面缓存 encoding: UTF-8 # 模板编码 prefix: classpath:/templates/ # 页面映射路径 suffix: .html # 试图后的后缀 mode: HTML5 # 模板模式 # 其他具体配置可参考org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties # 上面的配置实际上就是注入该类的属性值

demo示例

创建IndexController

 @Controller public class IndexController { // 返回视图页面 @RequestMapping("index") public String index(){ return "index"; } }

创建index.html

   <title>Title</title> Hello Thymeleaf! 

创建TestController

 @RestController public class TestController { // 返回整个页面 @RequestMapping("/test") public ModelAndView test(){ return new ModelAndView("test"); } }

创建test.html

   <title>Title</title> Hello Thymeleaf! </br> By: ModelAndView 

3.测试结果

4.Thymeleaf基础语法及使用

1.引入标签 

html标签里引入xmlns:th=”http://www.thymeleaf.org”才能使用th:*这样的语法

2.引入URL 

@{…} 

例如:

绝对路径 是访问绝对路径下的URL, 相对路径 是访问相对路径下的URL。

是引入默认的static下的css文件夹下的bootstrap文件,类似的标签有: th:href 和 th:src

3.获取变量 

通过${}取值,对于JavaBean的话,使用变量名.属性名获取

4.字符串替换


或者

注意:|…|中只能包含变量表达式${…},不能包含其他常量、条件表达式等

5.运算符 

   在表达式中可以使用各类算术运算符
   例如 (+, -, *, /, %)
   例如:th:with=”isEven=(${stat.number} % 1 == 0)”
   逻辑运算符 (>, <, =,==,!=)
   需要注意的是使用的时候需要转义

 th:if="${stat.number} > 1" th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' :<i style="color:transparent">来源gaodai$ma#com搞$$代**码网</i> 'Production')"

6.条件 

if/unless th:if是该标签在满足条件的时候才会显示,unless是不成立时候才显示

 Login

switch  thymeleaf支持switch结构,默认属性(default)用*表示

 <div> <p>User is an administrator</p><p>User is a manager</p><p>User is some other thing</p></div>

7.循环

 <tr> <td>Onions</td><td>2.41</td><td>yes</td></tr>

8.Utilities

内置在Context中,可以直接通过#访问
#dates
#calendars
#numbers
#strings
arrays
lists
sets
maps

5.小结

本文讲述了如何在Spring Boot中引入模板引擎Thymeleaf以及Thymeleaf基础语法和实际使用

本文GitHub地址:https://github.com/ishuibo/SpringAll

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持gaodaima搞代码网

以上就是SpringBoot引入Thymeleaf的实现方法的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:SpringBoot引入Thymeleaf的实现方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址