openplanning

Các đối tượng định nghĩa sẵn trong Thymeleaf

  1. Predefined Objects
  2. Basic Objects
  3. Utility Objects

1. Predefined Objects

Trong Thymeleaf có một vài đối tượng được định nghĩa sẵn và bạn có thể sử dụng chúng mọi nơi trong Thymeleaf Template, về cơ bản có 2 loại đối tượng như vậy đó là Các đối tượng cơ bản (Basic Objects), và các đối tượng tiện ích (Utility Objects):
Các đối tượng được định nghĩa trước này sẽ được tham chiếu (reference) theo tiêu chuẩn OGNL, bắt đầu với ký hiệu ( # ).

2. Basic Objects

Object
Class/Interface
Mô tả
#ctx
org.thymeleaf.context.IContext
org.thymeleaf.context.IWebContext
Một đối tượng thực hiện (implement) interface IContext hoặc IWebContext, tùy thuộc vào môi trường (Tiêu chuẩn hoặc Web).
#locale
java.util.Locale
Một đối tượng cung cấp các thông tin liên quan đến Locale (Địa phương).
#request
javax.servlet.http.HttpServletRequest
(Chỉ trong môi trường Web) Đối tượng HttpServletRequest.
#response
javax.servlet.http.HttpServletResponse
(Chỉ trong môi trường Web) Đối tượng HttpServletResponse.
#session
javax.servlet.http.HttpSession
(Chỉ trong môi trường Web) Đối tượng HttpSession.
#servletContext
javax.servlet.http.ServletContext
(Chỉ trong môi trường Web) Đối tượng ServletContext.
#ctx
#ctx là một đối tượng bối cảnh (Context object). Nó thực hiện (implements) interface org.thymeleaf.context.IContext hoặc org.thymeleaf.context.IWebContext, tùy thuộc vào môi trường (Tiêu chuẩn hoặc Web).
Hai đối tượng khác là #vars, #root cũng giống với #ctx. Nhưng #ctx được khuyến khích sử dụng thay vì 2 đối tượng kia.
Tùy thuộc vào môi trường, tiêu chuẩn hoặc Web, đối tượng #ctx có thể cung cấp cho bạn các thông tin:
<!--
 * ===============================================
 * See javadoc API for class org.thymeleaf.context.IContext
 * ===============================================
 -->

${#ctx.locale}
${#ctx.variableNames}

<!--
 * ================================================
 * See javadoc API for class org.thymeleaf.context.IWebContext
 * ================================================
  -->

${#ctx.request}
${#ctx.response}
${#ctx.session}
${#ctx.servletContext}
Trong môi trường Spring, đối tượng #ctx không hoạt động như mong đợi, ${#ctx.locale}, ${#ctx.request}, ${#ctx.response}, ${#ctx.request}, ${#ctx.servletContext} luôn trả về null. Bạn nên sử dụng các đối tượng #locale, #request, #response, #servletContext để thay thế.
#locale
Đối tượng #locale (java.util.Locale) cho bạn thông tin về môi trường mà ứng dụng đang hoạt động, chẳng hạn như khu vực địa lý, ngôn ngữ, văn hóa, kiểu định dạng số, kiểu định dạng ngày tháng và thời gian,...
predefined-object-locale.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="UTF-8" />
      <title>Predefined Objects</title>
   </head>
   <body>
       <h1>Predefined Object #locale</h1>
       <h3>#locale.locale</h3>
       <span th:utext="${#locale.country}"></span>
       <h3>#locale.language</h3>
       <span th:utext="${#locale.language}"></span>
   </body>
</html>
#request
predefined-object-request.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="UTF-8" />
      <title>Predefined Objects</title>
   </head>
   <body>
       <h1>Predefined Object #request</h1>
       <h3>#request.contextPath</h3>
       <span th:utext="${#request.contextPath}"></span>
       <h3>#request.requestURI</h3>
       <span th:utext="${#request.requestURI}"></span>
       <h3>#request.requestURL</h3>
       <span th:utext="${#request.requestURL}"></span>
   </body>
</html>
#response
predefined-object-response.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="UTF-8" />
      <title>Predefined Objects</title>
   </head>
   <body>
       <h1>Predefined Object #response</h1>
       <h3>#response.headerNames  (java.utils.Enumeration)</h3>
       <ul>
          <th:block  th:each="headerName : ${#request.headerNames}">
            <li th:utext="${headerName}">Header Name</li>
          </th:block>
       </ul>  
   </body>
</html>
#servletContext
predefined-object-servletContext.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="UTF-8" />
      <title>Predefined Objects</title>
   </head>
   <body>
       <h1>Predefined Object #servletContext</h1>
       <h3>#servletContext.attributeNames (java.utils.Enumeration)</h3>
       <ul>
          <th:block th:each="attrName : ${#servletContext.attributeNames}">
            <li th:utext="${attrName}">Attribute Name</li>
            <li th:utext="${#servletContext.getAttribute(attrName)}">Attribute Value</li>
          </th:block>
       </ul>  
   </body>
</html>
#session
Spring Controller
// ....
@RequestMapping("/predefined-object-session")
public String objectSession(HttpServletRequest request) {
   HttpSession session = request.getSession();
   session.setAttribute("mygreeting", "Hello Everyone!");
   return "predefined-object-session";
}
predefined-object-session.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="UTF-8" />
      <title>Predefined Objects</title>
   </head>
   <body>
       <h1>Predefined Object #session</h1>
       <h3>#session.getAttribute('mygreeting')</h3>
       <span th:utext="${#session.getAttribute('mygreeting')}"></span>  
   </body>
</html>

3. Utility Objects

Object
Class/Interface
Mô tả
#execInfo
org.thymeleaf.expression.ExecutionInfo
Thông tin về Template đang được xử lý.
#messages
org.thymeleaf.expression.Messages
Các phương thức để làm việc với các message.
#uris
org.thymeleaf.expression.Uris
Các phương thức để escape các phần của URLs/URIs.
#conversions
org.thymeleaf.expression.Conversions
Các phương thức để thực thi "dịch vụ chuyển đổi" (conversion service) đã được cấu hình (Nếu có).
#dates
javax.servlet.http.HttpSession
Các phương thức để định dạng đối tượng java.util.Date, hoặc lấy các thông tin liên quan như ngày, tháng, năm,..
#calendars
javax.servlet.http.ServletContext
Giống với #dates, nhưng với đối tượng java.util.Calendar.
#numbers
org.thymeleaf.expression.Numbers
Các phương thức để định dạng các đối tượng số (Number).
#strings
org.thymeleaf.expression.Strings
Các phương thức cho các đối tượng String. Chẳng hạn contains, startsWith, ...
#objects
org.thymeleaf.expression.Objects
Các phương thức cho các đối tượng nói chung.
#bools
org.thymeleaf.expression.Bools
Các phương thức cho việc đánh giá boolean.
#arrays
org.thymeleaf.expression.Arrays
Các phương thức cho các mảng (array).
#lists
org.thymeleaf.expression.Lists
Các phương thức cho lists.
#sets
org.thymeleaf.expression.Sets
Các phương thức cho sets.
#maps
org.thymeleaf.expression.Maps
Các phương thức cho maps.
#aggregates
org.thymeleaf.expression.Aggregates
Các phương thức để tính tổng, giá trị trung bình,.. trên một tập hợp (collection) hoặc mảng (array).
#ids
org.thymeleaf.expression.Ids
#execInfo
Đối tượng giúp bạn lấy được các thông tin về Template đang được xử lý.
@RequestMapping("/predefined-u-object-execInfo")
public String execInfo_object() {
      return "predefined-u-object-execInfo";
}
predefined-u-object-execInfo.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="UTF-8" />
      <title>Predefined Objects</title>
   </head>
   <body>
       <h1>#execInfo</h1>
       <h3>#execInfo.templateMode</h3>
       <span th:utext="${#execInfo.templateMode}"></span> 
       <h3>#execInfo.templateName</h3>
       <span th:utext="${#execInfo.templateName}"></span>
       <h3>#execInfo.now (java.util.Calendar)</h3>
       <span th:utext="${#execInfo.now}"></span>
   </body>
</html>
#uris
Đối tượng này cung cấp các phương thức để escape các phần của URLs/URIs.
predefined-u-object-uris.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="UTF-8" />
      <title>Predefined Objects</title>
   </head>
   <body>
       <h1>#uris</h1>
       <h4>#uris.escapePath('https://example.com?user=Tom&gender=Male')</h4>
       <span th:utext="${#uris.escapePath('https://example.com?user=Tom&gender=Male')}"></span>
       <h4>#uris.unescapePath('https://example.com%3Fuser=Tom&gender=Male')</h4>
       <span th:utext="${#uris.unescapePath('https://example.com%3Fuser=Tom&gender=Male')}"></span>  
   </body>
</html>
#dates
Cung cấp các phương thức để định dạng đối tượng java.util.Date, hoặc lấy các thông tin liên quan như ngày, tháng, năm,..
predefined-u-object-dates.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#dates</h1>
    <!-- Create a variable 'now' (java.util.Date), it exists in block -->
    <th:block th:with="now = ${#dates.createNow()}">
        <span th:utext="${now}"></span>
        <h4>#dates.format(now, 'yyyy-MM-dd HH:mm:ss')</h4>
        <span th:utext="${#dates.format( now , 'yyyy-MM-dd HH:mm:ss')}">Date String</span>
        <h4>#dates.year(now)</h4>
        <span th:utext="${#dates.year(now)}">Year</span>
        <h4>#dates.month(now)</h4>
        <span th:utext="${#dates.month(now)}">Month</span>
    </th:block>
</body>
</html>
#calendars
Cung cấp các phương thức để định dạng đối tượng java.util.Calendar, hoặc lấy các thông tin liên quan như ngày, tháng, năm,..
predefined-u-object-calendars.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#calendars</h1>
    <!-- Create a variable 'now' (java.util.Calendar), it exists in block -->
    <th:block th:with="now = ${#calendars.createNow()}">
        <span th:utext="${now}"></span>
        <h4>#calendars.format(now, 'yyyy-MM-dd HH:mm:ss')</h4>
        <span th:utext="${#dates.format( now , 'yyyy-MM-dd HH:mm:ss')}">Date String</span>
        <h4>#dates.year(now)</h4>
        <span th:utext="${#dates.year(now)}">Year</span>
        <h4>#dates.month(now)</h4>
        <span th:utext="${#dates.month(now)}">Month</span>
    </th:block>
</body>
</html>
#numbers
Cung cấp các phương thức để định dạng các đối tượng số (Number).
predefined-u-object-numbers.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#numbers</h1>
    <!-- Create a Number, it exists in block -->
   <th:block th:with="num = 12345.987654">
        <h4>num</h4>
        <span th:utext="${num}">Number</span>
        <h4>${#numbers.formatInteger(num,3)}</h4>
        <span th:utext="${#numbers.formatInteger(num,3)}">Number</span>
        <h4>${#numbers.formatInteger(num,3,'POINT')}</h4>
        <span th:utext="${#numbers.formatInteger(num,3,'POINT')}">Number</span>
        <h4>${#numbers.formatDecimal(num,3,'POINT',2,'COMMA')}</h4>
        <span th:utext="${#numbers.formatDecimal(num,3,'POINT',2,'COMMA')}">Number</span>
    </th:block>
</body>
</html>
#strings
#objects
Cung cấp các phương thức cho các đối tượng nói chung.
@RequestMapping("/predefined-u-object-objects")
public String objects_object(Model model) {
    // An array store null values.
    String[] colors = new String[] {"red", "blue", null, "green", null, "red"};
    model.addAttribute("colors", colors);
    return "predefined-u-object-objects";
}
predefined-u-object-objects.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#objects</h1>  
    <h4>#objects.arrayNullSafe(colors,'white')</h4>
    <ul>
        <li th:each="color : ${#objects.arrayNullSafe(colors,'white')}"
            th:utext="${color}"></li>
    </ul>
    <h4>And other methods..</h4>
</body>
</html>
#bools
Cung cấp các phương thức cho việc đánh giá boolean.
@RequestMapping("/predefined-u-object-bools")
public String bools_object(Model model) {
    // An array store null values.
    String[] colors = new String[] {"red", null , "blue"};
    model.addAttribute("colors", colors);
    return "predefined-u-object-bools";
}
predefined-u-object-bools.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#bools</h1>  
    <h4>Array: colors</h4>
    <ul>
        <li th:each="color : ${colors}"
            th:utext="${color}"></li>
    </ul>
    <h4>#bools.arrayIsTrue(colors)</h4>
    <ul>
        <li th:each="color : ${#bools.arrayIsTrue(colors)}"
            th:utext="${color}"></li>
    </ul>
    <h4>#bools.arrayIsFalse(colors)</h4>
    <ul>
        <li th:each="color : ${#bools.arrayIsFalse(colors)}"
            th:utext="${color}"></li>
    </ul>
    <h4>And other methods..</h4>
</body>
</html>
#arrays
Cung cấp các phương thức cho các mảng (array).
@RequestMapping("/predefined-u-object-arrays")
public String arrays_object(Model model) {
    String[] colors = new String[] {"red", null , "blue"};
    model.addAttribute("colors", colors);
    return "predefined-u-object-arrays";
}
predefined-u-object-arrays.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#arrays</h1>  
    <h4>Array: colors</h4>
    <ul>
        <li th:each="color : ${colors}"
            th:utext="${color}"></li>
    </ul>
    <h4>#arrays.isEmpty(colors)</h4>
    <span th:utext="${#arrays.isEmpty(colors)}"></span>
    <h4>#arrays.length(colors)</h4>
    <span th:utext="${#arrays.length(colors)}"></span>
    <h4>#arrays.contains(colors,'red')</h4>
    <span th:utext="${#arrays.contains(colors,'red')}"></span>
    <h4>And other methods..</h4>
</body>
</html>
#lists
Cung cấp các phương thức cho các đối tượng lists.
@RequestMapping("/predefined-u-object-lists")
public String lists_object(Model model) {
    String[] array = new String[] {"red", "blue", "green"};
    List<String> colors = Arrays.asList(array);
    model.addAttribute("colors", colors);
    return "predefined-u-object-lists";
}
predefined-u-object-lists.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#lists</h1>  
    <h4>List: colors</h4>
    <ul>
        <li th:each="color : ${colors}"
            th:utext="${color}"></li>
    </ul>
    <h4>#lists.sort(colors)</h4>
    <ul>
        <li th:each="color : ${#lists.sort(colors)}"
            th:utext="${color}"></li>
    </ul>
    <h4>#lists.isEmpty(colors)</h4>
    <span th:utext="${#lists.isEmpty(colors)}"></span>
    <h4>#lists.size(colors)</h4>
    <span th:utext="${#lists.size(colors)}"></span>
    <h4>#lists.contains(colors,'red')</h4>
    <span th:utext="${#lists.contains(colors,'red')}"></span>
    <h4>And other methods..</h4>
</body>
</html>
#sets
Cung cấp các phương thức cho các đối tượng sets.
@RequestMapping("/predefined-u-object-sets")
public String sets_object(Model model) {
    Set<String> colors = new HashSet<String>();
    colors.add("red");
    colors.add("blue");
    colors.add("green");
    model.addAttribute("colors", colors);
    return "predefined-u-object-sets";
}
predefined-u-object-sets.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#sets</h1>  
    <h4>List: colors</h4>
    <ul>
        <li th:each="color : ${colors}"
            th:utext="${color}"></li>
    </ul>
    <h4>#sets.isEmpty(colors)</h4>
    <span th:utext="${#sets.isEmpty(colors)}"></span>
    <h4>#sets.size(colors)</h4>
    <span th:utext="${#sets.size(colors)}"></span>
    <h4>#sets.contains(colors,'red')</h4>
    <span th:utext="${#sets.contains(colors,'red')}"></span>
    <h4>And other methods..</h4>
</body>
</html>
#maps
Cung cấp các phương thức cho các đối tượng maps.
@RequestMapping("/predefined-u-object-maps")
public String maps_object(Model model) {
    Map<String,String> contacts = new HashMap<String,String>();
    contacts.put("111 222","Tom");
    contacts.put("111 333","Jerry");
    contacts.put("111 444","Donald");
    model.addAttribute("contacts", contacts);
    return "predefined-u-object-maps";
}
predefined-u-object-maps.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#maps</h1>  
    <h4>Map: contacts</h4>
    <h4>#maps.isEmpty(contacts)</h4>
    <span th:utext="${#maps.isEmpty(contacts)}"></span>
    <h4>#maps.size(contacts)</h4>
    <span th:utext="${#maps.size(contacts)}"></span>
    <h4>And other methods..</h4>
</body>
</html>
#aggregates
Cung cấp các phương thức để tính tổng, giá trị trung bình,.. trên một tập hợp (collection) hoặc một mảng (array).
#aggregates
@RequestMapping("/predefined-u-object-aggregates")
public String aggregates_object(Model model) {
    double[] salaries = new double[] {100, 200, 500};
    model.addAttribute("salaries", salaries);
    return "predefined-u-object-aggregates";
}
predefined-u-object-aggregates.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Predefined Objects</title>
</head>
<body>
    <h1>#aggregates</h1>  
    <h4>Array: salaries</h4>
    <ul>
        <li th:each="salary : ${salaries}"
            th:utext="${salary}"></li>
    </ul>
    <h4>#aggregates.avg(salaries)</h4>
    <span th:utext="${#aggregates.avg(salaries)}"></span>
  
    <h4>#aggregates.sum(salaries)</h4>
    <span th:utext="${#aggregates.sum(salaries)}"></span>
</body>
</html>
#ids