Предопределенные объекты в Thymeleaf
View more Tutorials:
В Thymeleaf имеются некоторые предопределенные объекты и вы можете использовать их везде в Thymeleaf Template. В основном имеются 2 вида объекта это Базовые объекты (Basic Objects), и Утилитарные объекты (Utility Objects):
Эти предопределенные объекты будут ссылаться (reference) в соответствии со стандартом OGNL, начиная с символа ( # ).
Объект | Класс/Интерфейс | Описание |
#ctx | org.thymeleaf.context.IContext org.thymeleaf.context.IWebContext | Объект выполняет (implement) интерфейс IContext или IWebContext, в зависимости от среды (Стандартная или Web). |
#locale | java.util.Locale | Объект предоставляет информацию связанную с Locale (Локалом). |
#request | javax.servlet.http.HttpServletRequest | (Только в среде Web) Объект HttpServletRequest. |
#response | javax.servlet.http.HttpServletResponse | (Только в среде Web) Объект HttpServletResponse. |
#session | javax.servlet.http.HttpSession | (Только в среде Web) Объект HttpSession. |
#servletContext | javax.servlet.http.ServletContext | (Только в среде Web) Объект ServletContext. |
#ctx
#ctx это контекстный объект(Context object). Он выполняет (implements) интерфейс org.thymeleaf.context.IContext или org.thymeleaf.context.IWebContext, в зависимости от среды (Стандартная или Web).
Два других объекта это #vars, #root похожи на #ctx. Но #ctx рекомендуется для использования вместо тех 2-х объектов.
В зависимости от среды, стандартной или Web, объект #ctx может предоставить вам информацию:
<!-- * =============================================== * 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}
В среде Spring, объект #ctx не работает в соответствии с ожиданиями, ${#ctx.locale}, ${#ctx.request}, ${#ctx.response}, ${#ctx.request}, ${#ctx.servletContext} всегда возвращает null. Вам стоит использовать объекты #locale, #request, #response, #servletContext для замены.
#locale
Объект #locale (java.util.Locale) дает вам информацию о среде в которой работает приложение, например географическое расположение, язык, культура, цифровой формат, формат даты и времени,...
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>

Объект | Класс/Интерфейс | Описание |
#execInfo | org.thymeleaf.expression.ExecutionInfo | Информация про Template обрабатывается. |
#messages | org.thymeleaf.expression.Messages | Методы для работы с message. |
#uris | org.thymeleaf.expression.Uris | Методы для escape части у URLs/URIs. |
#conversions | org.thymeleaf.expression.Conversions | Методы для выполнения конфигурированного "конверсионного сервиса" (conversion service) (Если имеется). |
#dates | javax.servlet.http.HttpSession | Методы для форматирования объекта java.util.Date, или получения связанной информации как день, месяц, год,.. |
#calendars | javax.servlet.http.ServletContext | Похоже на #dates, но с объектом java.util.Calendar. |
#numbers | org.thymeleaf.expression.Numbers | Методы для форматирования числовых объектов (Number). |
#strings | org.thymeleaf.expression.Strings | Методы для объектов String. Например contains, startsWith, ... |
#objects | org.thymeleaf.expression.Objects | Методы для объектов в общем. |
#bools | org.thymeleaf.expression.Bools | Методы для оценки boolean. |
#arrays | org.thymeleaf.expression.Arrays | Методы для массивов (array). |
#lists | org.thymeleaf.expression.Lists | Методы для lists. |
#sets | org.thymeleaf.expression.Sets | Методы для sets. |
#maps | org.thymeleaf.expression.Maps | Методы для maps. |
#aggregates | org.thymeleaf.expression.Aggregates | Методы для расчета суммы, среднего значения,.. на коллекции (collection) или массиве (array). |
#ids | org.thymeleaf.expression.Ids |
Смотрите так же:
- org.thymeleaf.expression.ExecutionInfo
- org.thymeleaf.expression.Messages
- org.thymeleaf.expression.Uris
- org.thymeleaf.expression.Conversions
- org.thymeleaf.expression.Dates
- org.thymeleaf.expression.Calendars
- org.thymeleaf.expression.Numbers
- org.thymeleaf.expression.Strings
- org.thymeleaf.expression.Objects
- org.thymeleaf.expression.Bools
- org.thymeleaf.expression.Arrays
- org.thymeleaf.expression.Lists
- org.thymeleaf.expression.Sets
- org.thymeleaf.expression.Maps
- org.thymeleaf.expression.Aggregates
- org.thymeleaf.expression.Ids
#execInfo
Объект помогает вам получить информацию про Template обрабатывается.
@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
Данный объект определяет методы для escape частей у 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
Предоставляет методы для форматирования объекта java.util.Date, или получения связанной информации как день, месяц, год,..
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
Предоставляет методы для форматирования объектов java.util.Calendar, или получения связанной информации как день, месяц, год,..
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
Предоставляет методы для форматирования числовых объектов (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
Предоставляет методля для объектов в общем.
@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
Предоставляет метод для оценки 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
Предоставляет методы для массивов (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
Предоставляет методы для объектов 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
Предоставляет методы для объектов 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
Предоставляет методы для объектов 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
Предоставляет методы для расчета суммы, среднего значения,.. на коллекции (collection) или массиве (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>
