thymeleaf 基本表達式


 

 如需了解thymeleaf以及thymeleaf整合spring,請參考《Thymeleaf模板引擎使用》、《Thymeleaf 集成spring

 

${}

變量表達式(美元表達式,哈哈),用於訪問容器上下文環境中的變量,功能同jstl中${}。

例如:

protected void doPost(HttpServletRequest req, HttpServletResponse resp) 

throws ServletException, IOException {

...

//Create Servlet context

WebContext ctx = new WebContext(req, resp, this.getServletContext(), req.getLocale());

ctx.setVariable("helloword","hello thymeleaf,wellcome!");

//Executing template engine

templateEngine.process("home", ctx, resp.getWriter());

}

模板頁面訪問變量

<p><span th:text="${helloword}"></span></p>

 

*{}

選擇表達式(星號表達式)。選擇表達式與變量表達式有一個重要的區別:選擇表達式計算的是選定的對象,而不是整個環境變量映射。也就是:只要是沒有選擇的對象,選擇表達式與變量表達式的語法是完全一樣的。那什么是選擇的對象呢?是一個:th:object對象屬性綁定的對象。

例如:

<div th: obj ect=" ${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>

上例中,選擇表達式選擇的是th:object對象屬性綁定的session. user對象中的屬性。

 

#{}

消息表達式(井號表達式,資源表達式)。通常與th:text屬性一起使用,指明聲明了th:text的標簽的文本是#{}中的key所對應的value,而標簽內的文本將不會顯示

例如:

新建/WEB-INF/templates/home.html,段落

<p th: text=" #{home. welcome}" >This text will not be show! </p>

新建/WEB-INF/templates/home.propertieshome.welcome

home.welcome=this messages is from home.properties!

測試結果:

從測試結果可以看出,消息表達式通常用於顯示頁面靜態文本,將靜態文本維護在properties文件中也方面維護,做國際化等。

 

@{}

超鏈接url表達式。

例如:

<script th:src="@{/resources/js/jquery/jquery.json-2.4.min.js}"

 

#maps

工具對象表達式。常用於日期、集合、數組對象的訪問。這些工具對象就像是java對象,可以訪問對應java對象的方法來進行各種操作

例如:

<div th:if="${#maps.size(stuReqBean.students[__${rowStat.index}__].score) != 0}">

<label>${score.key}:</label><input type="text" th:value="${score.value}"></input>

</div>

<div th:if="${#maps.isEmpty(stuReqBean.students[__${rowStat.index}__].score)}">

...do something...

</div>

 

其他工具對象表達式還有:

#dates

#calendars

#numbers 

#strings

#objects

#bools

#arrays

#lists

#sets

 

更多詳細表達式請訪問:http://www.thymeleaf.org


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM