Thymeleaf三种模式:
- HTML模板模式
- XML模板模式
- TEXT模板模式
JSP模板的代码片段在模板解析之前不能通过浏览器显示
<form:inputText name="userName" value="${user.name}" />
Thymeleaf不包括任何非HTML标签,不存在这个问题
<input type="text" name="userName" value="James Carrot" th:value="${user.name}" />
模板引擎是org.thymeleaf.ITemplateEngine接口的实现
创建一个实例并把TemplateResolver设置为他的属性
templateEngine = new TemplateEngine()
templateEngine.setTemplateResolver(templateResolver)
创建一个简单页面
<!DOCTYPE html>
<html xmlns:th="http://www.thmeleaf.org">
<head>
<title>...</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all"
href=".../gtvg.css" th:href="@{/css/gtvg.css}" />
</head>
<body>
<p th:text="#{home.welcome}">welcome to our grocery store!</p>
</body>
</html>
H5规定自定义属性由data-开头,因此把上面所有th:xxx 改成 data-th-xxx 就合法了
(仅在HTML模板模式如此,其他模式中th:xxx更为通用)
消息(文本的外部化片段): #{…}
th:text 属性,用于计算其表达式并将结果设置为标签的标签体,有效替换
外部文本的位置通过
org.thymeleaf.messageresolver.IMessageResolver实现,通常基于.properties文件
标准解释器会去同一个文件目录下找同名.property文件寻找外部文本
${x} 返回存储在Thymeleaf上下文中的变量x作为请求属性
${param.x} ...作为请求参数
${session.x} ...作为会话属性
${application.x} ...作为上下文属性
th:utext (unescaped text非转译文本)
${...} 变量表达式
*{...} 选择变量表达式
#{...} 消息表达式
@{...} 链接网址表达式
~{...} 片段表达式
- 字符串连接
算数运算符
+ - \* / %
比较运算符
> < >= <=
条件运算符
if-then \(if\) ? \(then\)
if-then-else \(if\) ? \(then\) : \(else\)
default \(value\) ?: \(defaultvalue\)
哑操作符 _ 就相当于不执行任何操作null
例如
th:text="${user.name}?:_"
如果根据访客语言和名字动态回复
<p th:utext="#{home.welcome(${session.user.name})}">
welcome to our grocery store, sebastian pepper
</p>
这句话用OGNL语法就是
((User) ctx.getVariable("session").get("user")).getName();
基本对象表达式(见附录A)
#ctx 上下文对象
#vars 上下文变量
#locale 上下文区域设置
#request (仅在web contexts中)HttpServletRequest对象
#response (仅在web上下文中)HttpServletRequest对象
#session (仅在web上下文中)HttpSession对象
#servletContext (仅在web上下文中)ServletContext对象
工具表达式(见附录B)
JSP模板的代码片段在模板解析之前不能通过浏览器显示
#execInfo
#messages
#uris
#conversions
#dates
#calendars
#numbers
#strings
#objects
#bools
#arrays
#lists
#sets
#maps
#aggregates
#ids
星号表达式:
类似于美元表达式 *{…}
默认表达式
th:text="*{age}?:'(no age specified)'"
等价于
th:text="*{age != null}? *{age} : '(no age specified)'"
预处理表达式:
优先处理的表达式
${expression}
设置属性
th:attrname
设置多个属性
th:attrname1-attrname2
属性前缀和后缀
th:attrappend th:attrprepend
...class="xxx" th:attrappend="class=${' '+cssStyle}" />
固定值得布尔属性
th:cheched="${user.active}" />
循环迭代
th:each="prod, iterStat: ${prods}"
判断语句
a href="..." th:href=",,," th:if="${not #lists.isEmpty(prod.comments)}"
switch语句
<div th:switch="${user.role}">
可参数化片段签名
<div th:fragment="frag (onevar, twovar)">
不带片段参数的片段局部变量
<div th:fragment="frag"> /*在一个footer.html页面定义一个版权声明片段,
然后在别的页面th:insert="~{footer :: copy}">或th:insert="footer :: copy">
模板内部断言
<div th:assert="${onevar},(${twovar} != 43">
删除字段
th:remove
内联表达式
<p>Hello, [[${session.user.name}]]!</p>
等同于
<p>hello, <span th:text="${session.user.name}">Sebastian</span>!</p>
禁用内联
th:inline="none"
内联js
<script th:inline="javascript">