Thymeleaf语法

1、th属性

html有的属性,Thymeleaf基本都有,而常用的属性大概有七八个。其中th属性执行的优先级从1~8,数字越低优先级越高。

  1. th:text :设置当前元素的文本内容,相同功能的还有th:utext,两者的区别在于前者不会转义html标签,后者会。优先级不高:order=7

  2. th:value:设置当前元素的value值,类似修改指定属性的还有th:src,th:href。优先级不高:order=6

  3. th:each:遍历循环元素,和th:text或th:value一起使用。注意该属性修饰的标签位置,详细往后看。优先级很高:order=2

  4. th:if:条件判断,类似的还有th:unless,th:switch,th:case。优先级较高:order=3

  5. th:insert:代码块引入,类似的还有th:replace,th:include,三者的区别较大,若使用不恰当会破坏html结构,常用于公共代码块提取的场景。优先级最高:order=1

  6. th:fragment:定义代码块,方便被th:insert引用。优先级最低:order=8

  7. th:object:声明变量,一般和*{}一起配合使用,达到偷懒的效果。优先级一般:order=4

  8. th:attr:修改任意属性,实际开发中用的较少,因为有丰富的其他th属性帮忙,类似的还有th:attrappend,th:attrprepend。优先级一般:order=5

使用Thymeleaf属性需要注意点以下五点:

  1. 若要使用Thymeleaf语法,首先要声明名称空间: xmlns:th="http://www.thymeleaf.org"

  2. 设置文本内容 th:text,设置input的值 th:value,循环输出 th:each,条件判断 th:if,插入代码块 th:insert,定义代码块 th:fragment,声明变量 th:object

  3. th:each 的用法需要格外注意,打个比方:如果你要循环一个div中的p标签,则th:each属性必须放在p标签上。若你将th:each属性放在div上,则循环的是将整个div。

  4. 变量表达式中提供了很多的内置方法,该内置方法是用#开头,请不要与#{}消息表达式弄混。

  5. th:insert,th:replace,th:include 三种插入代码块的效果相似,但区别很大。

例子:

在后台绑定数据

@Controller
public class ThController {
    @RequestMapping("/success")
    public String success(Model model){
        //1.绑定一个字符串
        model.addAttribute("msg","this is a <b>String</b>");
        model.addAttribute("msgUtext","this is a <b>String</b>");

        //2.绑定一个pojo对象--先去创建一个Emp
        Emp emp=new Emp("张三",20);
        model.addAttribute("emp",emp);

        //3.绑定一个list
        List list=new ArrayList();
        list.add(emp);
        list.add(new Emp("李四",20));
        list.add(new Emp("王五",20));
        model.addAttribute("emps",list);

        //4.绑定一个map
        Map<String,Object> map=new HashMap<>();
        map.put("Boss",new Emp("boss",30));
        model.addAttribute("map",map);

        //前缀:classpath:/templates/ success  后缀.html
        return "success";
    }
}

在html中使用thmeleaf语法获取数据

<!--th:text 设置当前元素的文本内容,常用,优先级不高-->
<p th:text="${msg}"></p>
<p th:utext="${msgUtext}"></p>

<!--th:value 设置当前元素的value值,常用,优先级仅比th:text高-->
姓名:<input type="text" th:value="${emp.name}" />
年龄:<input type="text" th:value="${emp.age}" />
--------------------------------------------------------------
<!--th:each 遍历列表,常用,优先级很高,仅此于代码块的插入,遍历被修饰的元素-->
<table border="1px" th:width="200px">
    <thead>
        <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        <tr th:each="e:${emps}">
            <td>编号</td>
            <td th:text="${e.name}"></td>
            <td th:text="${e.age}"></td>
            <td>删除/修改</td>
        </tr>
    </tbody>
    <tbody>
    <tr th:each="e,eState:${emps}">
        <td th:text="${eState.index+1}"></td>
        <td th:text="${e.name}"></td>
        <td th:text="${e.age}"></td>
        <td>删除/修改</td>
    </tr>
    </tbody>
</table>

th:each="e,eState : ${emps}"
其中e为循环的每一项,eState是下标属性(可省略),eState属性包括:

index:列表状态的序号,从0开始;
count:列表状态的序号,从1开始;
size:列表状态,列表数据条数;
current:列表状态,当前数据对象
even:列表状态,是否为奇数,boolean类型
odd:列表状态,是否为偶数,boolean类型
first:列表状态,是否为第一条,boolean类型
last:列表状态,是否为最后一条,boolean类型

th:if

gt:great than(大于)

ge:great equal(大于等于)

eq:equal(等于)

lt:less than(小于)

le:less equal(小于等于)

ne:not equal(不等于)

2、标准表达式语法

变量表达式使用频率最高,其功能也是非常的丰富。所以我们先从简单的代码块表达式开始,然后是消息表达式,再是链接表达式,最后是变量表达式,随带介绍选择变量表达式。

~{…} 代码块表达式
支持两种语法结构:
推荐:~{templatename::fragmentname}
支持:~{templatename::#id}
templatename:模版名,Thymeleaf会根据模版名解析完整路径:/resources/templates/templatename.html,要注意文件的路径。
fragmentname:片段名,Thymeleaf通过th:fragment声明定义代码块,即:th:fragment="fragmentname"
id:HTML的id选择器,使用时要在前面加上#号,不支持class选择器。
代码块表达式的使用:
代码块表达式需要配合th属性(th:insert,th:replace,th:include)一起使用。
th:insert:将代码块片段整个插入到使用了th:insert的HTML标签中
th:replace:将代码块片段整个替换使用了th:replace的HTML标签中
th:include:将代码块片段包含的内容插入到使用了th:include的HTML标签中
例子:
<!--th:fragment定义代码块标识-->
<footer th:fragment="copy">
&copy; 2019 The Good Thymes Virtual Grocery
</footer>

<!--三种不同的引入方式-->
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>
使用后的结果其实如下:

<!--th:insert是在div中插入代码块,即多了一层div-->
<div>
<footer>
&copy; 2019 The Good Thymes Virtual Grocery
</footer>
</div>
<!--th:replace是将代码块代替当前div,其html结构和之前一致-->
<footer>
&copy; 2019 The Good Thymes Virtual Grocery
</footer>
<!--th:include是将代码块footer的内容插入到div中,即少了一层footer-->
<div>
&copy; 2019 The Good Thymes Virtual Grocery
</div>
#{…} 消息表达式
消息表达式一般用于国际化的场景。结构:th:text="#{msg}" 。下面有一块再详细介绍。
@{…} 链接表达式
链接表达式好处:不管是静态资源的引用,form表单的请求,凡是链接都可以用@{…} 。这样可以动态获取项目路径,即便项目名变了,依然可以正常访问。
#修改项目名,链接表达式会自动修改路径,避免资源文件找不到
server.context-path=/itdragon

链接表达式结构:
无参:@{/xxx}
有参:@{/xxx(k1=v1,k2=v2)} 对应url结构:xxx?k1=v1&k2=v2
引入本地资源:@{/项目本地的资源路径}
引入外部资源:@{/webjars/资源在jar包中的路径}
例子:
<!--引入外部资源-->
<link th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
<!--引入本地资源-->
<link th:href="@{/main/css/itdragon.css}" rel="stylesheet">
<!--表单提交路径-->
<form class="form-login" th:action="@{/user/login}" th:method="post" >
<!--超链接跳转路径附带参数-->
<a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>

${…}变量表达式
变量表达式有丰富的内置方法,使其更强大,更方便。
变量表达式功能:
可以获取对象的属性和方法
可以使用ctx,vars,locale,request,response,session,servletContext内置对象
可以使用dates,numbers,strings,objects,arrays,lists,sets,maps等内置方法

3、常用的内置对象

 ctx :上下文对象。

vars :上下文变量。

locale:上下文的语言环境。

request:(仅在web上下文)的 HttpServletRequest 对象。

response:(仅在web上下文)的 HttpServletResponse 对象。

session:(仅在web上下文)的 HttpSession 对象。

servletContext:(仅在web上下文)的 ServletContext 对象

例子:

// java 代码将用户名放在session中 session.setAttribute("userinfo",username);

// Thymeleaf通过内置对象直接获取 th:text="${session.userinfo}"

4、常用的内置方法

strings:字符串格式化方法,常用的Java方法它都有。比如:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsIgnoreCase等

numbers:数值格式化方法,常用的方法有:formatDecimal等

bools:布尔方法,常用的方法有:isTrue,isFalse等

arrays:数组方法,常用的方法有:toArray,length,isEmpty,contains,containsAll等

lists,sets:集合方法,常用的方法有:toList,size,isEmpty,contains,containsAll,sort等

maps:对象方法,常用的方法有:size,isEmpty,containsKey,containsValue等

dates:日期方法,常用的方法有:format,year,month,hour,createNow等

例子:

<h3>#strings </h3>
<div th:if="${not #strings.isEmpty(itdragonStr)}" >
<p>Old Str : <span th:text="${itdragonStr}"/></p>
<p>toUpperCase : <span th:text="${#strings.toUpperCase(itdragonStr)}"/></p>
<p>toLowerCase : <span th:text="${#strings.toLowerCase(itdragonStr)}"/></p>
<p>equals : <span th:text="${#strings.equals(itdragonStr, 'itdragonblog')}"/></p>
<p>equalsIgnoreCase : <span th:text="${#strings.equalsIgnoreCase(itdragonStr, 'itdragonblog')}"/></p>
<p>indexOf : <span th:text="${#strings.indexOf(itdragonStr, 'r')}"/></p>
<p>substring : <span th:text="${#strings.substring(itdragonStr, 2, 8)}"/></p>
<p>replace : <span th:text="${#strings.replace(itdragonStr, 'it', 'IT')}"/></p>
<p>startsWith : <span th:text="${#strings.startsWith(itdragonStr, 'it')}"/></p>
<p>contains : <span th:text="${#strings.contains(itdragonStr, 'IT')}"/></p>
</div>

原文地址:https://www.cnblogs.com/h-z-y/p/14255558.html