Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。相似JSP,Velocity,FreeMaker等,它也能够轻易的与Spring MVC等Web框架进行集成做为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特色是可以直接在浏览器中打开并正确显示模板页面,而不须要启动整个Web应用。html
好了,大家说了咱们已经习惯使用了什么 velocity,FreMaker,beetle之类的模版,那么到底好在哪里呢? 比一比吧 Thymeleaf是不同凡响的,由于它使用了天然的模板技术。这意味着Thymeleaf的模板语法并不会破坏文档的结构,模板依旧是有效的XML文档。模板还能够用做工做原型,Thymeleaf会在运行期替换掉静态值。Velocity与FreeMarker则是连续的文本处理器。java
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Hello World!</title> </head> <body> <h1 th:inline="text">Hello springboot v.2</h1> <p th:text="${hello}"></p> </body> <html>
@Controller publicclass TemplateController { @RequestMapping("/") public String helloHtml(Map<String,Object> map){ map.put("hello","from TemplateController.helloHtml"); return"/index"; } }
classpath:/META-INF/resources/index.html classpath:/resources/index.html classpath:/static/index.html calsspath:/public/index.html
spring.thymeleaf.prefix: /templates/ spring.thymeleaf.suffix: .html
thymeleaf中的默认这是能够查看org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties这个类的属性spring
# Allow Thymeleaf templates to be reloaded at dev time spring.thymeleaf.cache: false server.tomcat.access_log_enabled: true server.tomcat.basedir: target/tomcat
在html页面中引入thymeleaf命名空间,即 <html xmlns:th=http://www.thymeleaf.org></html>
,此时在html模板文件中动态的属性使用th:命名空间修饰。浏览器
引用静态资源文件,好比CSS和JS文件,语法格式为@{}
,如@{/js/user/user.js}
会引入/static目录下的/js/user/user.js文件。spring-mvc
访问spring-mvc中model的属性,语法格式为${}
,如${user.id}
能够获取model里的user对象的id属性。缓存
循环,在html的标签中,加入th:each="value:${list}"
形式的属性,如<span th:each="user:${users}"></span>
能够迭代users的数据 。tomcat
判断,在html标签中,加入th:if="表达式"
能够根据条件显示html元素 <span th:if="${not #lists.isEmpty(blog.publishTime)}"> <span id="publishtime" th:text="${#dates.format(blog.publishTime, 'yyyy-MM-dd HH:mm:ss')}"></span></span>
以上代码表示若blog.publishTime时间不为空,则显示时间springboot
时间的格式化,${#dates.format(blog.publishTime,'yyyy-MM-dd HH:mm:ss')}
表示将时间格式化为yyyy-MM-dd HH:mm:ss
格式化写法与Java格式化Date的写法是一致的。mvc
字符串拼接有两种形式 好比拼接这样一个URL:/blog/delete/{blogId}
app
th:href="'/blog/delete/' + ${blog.id }"
th:href="${'/blog/delete/' + blog.id }"