SpringBoot-thymeleaf模板语法

    第一次用springboot构建项目,后台对象传给前台显示的时候,因为用的是thymeleaf模板,所以需要用它规定好的格式进行数据的动态显示,开始查看官方文档进行记录:

thymeleaf模板语法,都以th属性开头,如:    <span th:text="...">

一,thymeleaf-简单表达式

1.变量表达式

Thymeleaf模板引擎在进行模板渲染时,还会附带一个Context存放进行模板渲染的变量,在模板中定义的表达式本质上就是从Context中获取对应的变量的值   如: <p>Today is: <span th:text="${day}">2 November 2016</span>.</p>

假设day的值为2018年11月2日,那么渲染结果为:<p>Today is: 2018年11月2日.</p>。
注意 : 渲染后,模板中span值2 November 2016将被覆盖,从中也可以看出,前台可以先放好静态的数据,当后台没有数据传过来的时候可以显示静态的数据进行显示,做好前后端分离。

2.选择或星号表达式

可以简单理解为内层是对外层对象的引用  如:

<div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
    <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
    <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>

等同于以下方式:

<div>
  <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>
  <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
  <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>

如果没有与th:object结合使用,*{}与${}效果一样,因为其范围自动扩展到context。
 


3.文字国际化表达式

文字国际化表达式允许我们从一个外部文件获取区域文字信息(.properties) 
使用Key-Value方式,还可以提供一组参数(可选).

#{main.title}
#{message.entrycreated(${entryId})}

模板引用:

<table>
    <th th:text="#{header.address.city}">...</th>
    <th th:text="#{header.address.country}">...</th>
</table>
4.URL表达式

URL表达式指的是把一个有用的上下文或会话信息添加到URL,这个过程经常被叫做URL重写。 
Thymeleaf对于URL的处理是通过语法@{…}来处理的

<!— 绝对路径 —>
<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>

<!— 相对路径 带参数—>
<!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>

<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

Thymeleaf支持相对路径和绝对路径
(orderId=${o.id})表示将括号内的内容作为URL参数处理
@{...}表达式中可以通过{orderId}访问Context中的orderId变量
@{/order}是Context相关的相对路径,在渲染时会自动添加上当前Web应用的Context名字,假设context名字为app,那么结果应该是/app/order
 

二.thymeleaf-字面值

    1.文本文字:’one text’, ‘Another one!’,… 
  2.文字数量:0, 34, 3.0, 12.3,… 
  3.布尔型常量:true, false 
  4.空的文字:null 
  5.文字标记:one, sometext, main,… 

三:thymeleaf-文本处理

1.字符串拼接:+

<span th:text="'Welcome to our application, ' + ${user.name} + '!'">

2.文字替换:|The name is ${name}|

<span th:text="|Welcome to our application, ${user.name}!|">

相比以上两种方式都可以实现字符串合并,但是,|…|中只能包含变量表达式${…},不能包含其他常量、条件表达式等。

--------------------------------------------------暂时先记录这些,以后用到再补充--------------------------------------------------------

发布了15 篇原创文章 · 获赞 30 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/qq_39848608/article/details/88807940