Themleaf
thymeleaf 是新一代的模板引擎,在spring4.0中推荐使用thymeleaf来做前端模版引擎。
- Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
- Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
- Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
springboot整合themleaf
1. 项目依赖
org.springframework.boot
spring-boot-starter-thymeleaf
net.sourceforge.nekohtml
nekohtml
1.9.22
2. application.properties配置
#thymeleaf
#默认到resource/templates目录下寻找
spring.thymeleaf.suffix=.html
spring.thymeleaf.check-template-location=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
spring.thymeleaf.mode=LEGACYHTML5
3. 工程结构

HelloController
import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /* * @author uv * @date 2018/9/25 18:06 * */ @Controller public class HelloController { @RequestMapping("hello") public String hello(String name, Model model) { List
list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); model.addAttribute("name", name); model.addAttribute("strList", list); model.addAttribute("show", false); return "hello"; } }
Hello.html
引用命名空间
Title
可见
4. 运行结果

5. 常用标签
| 关键字 | 功能介绍 | 案例 |
|---|---|---|
| th:id | 替换id | |
| th:text | 文本替换 |
|
| th:utext | 支持html的文本替换 |
|
| th:object | 替换对象 |
|
| th:value | 属性赋值 | |
| th:with | 变量赋值运算 |
|
| th:style | 设置样式 | th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''" |
| th:onclick | 点击事件 | th:onclick="'getCollect()'" |
| th:each | 属性赋值 | tr th:each="user,userStat:${users}"> |
| th:if | 判断条件 | |
| th:unless | 和th:if判断相反 | Login |
| th:href | 链接地址 | Login /> |
| th:switch | 多路选择 配合th:case 使用 |
|
| th:case | th:switch的一个分支 |
|
| th:fragment | 布局标签,定义一个代码片段,方便其它地方引用 |
|
| th:include | 布局标签,替换内容到引入的文件 | /> |
| th:replace | 布局标签,替换整个标签到引入的文件 |
|
| th:selected | selected选择框 选中 | th:selected="(${xxx.id} == ${configObj.dd})" |
| th:src | 图片类地址引入 | |
| th:inline | 定义js脚本可以使用变量 | |
| th:action | 表单提交的地址 |
|
| th:remove | 删除某个属性 | |
| th:attr | 设置标签属性,多个属性可以用逗号分隔 | 比如 th:attr="src=@{/image/aa.jpg},title=#{logo}",此标签不太优雅,一般用的比较少。 |
更多详细用法请参考官网:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#introducing-thymeleaf
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/209007.html原文链接:https://javaforall.net
