http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#using-texts
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
@RequestMapping("/")
public String index(Model model) {
model.addAttribute("convidados", convidadoRepository.findAll());
return "index";
}
src/main/resources/messages.properties
texto.messsage=Texto Teste
<html xmlns:th="http://www.thymeleaf.org"></html>
<p th:text="${convidados}"></p>
<p th:text="#{texto.messsage}"></p>
Variable Expressions: ${...}
Selection Variable Expressions: *{...}
Message Expressions: #{...}
Link URL Expressions: @{...}
Fragment Expressions: ~{...}
Text literals: 'one text', 'Another one!',…
Number literals: 0, 34, 3.0, 12.3,…
Boolean literals: true, false
Null literal: null
Literal tokens: one, sometext, main,…
String concatenation: +
Literal substitutions: |The name is ${name}|
Binary operators: +, -, *, /, %
Minus sign (unary operator): -
Binary operators: and, or
Boolean negation (unary operator): !, not
Comparators: >, <, >=, <= (gt, lt, ge, le)
Equality operators: ==, != (eq, ne)
If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)
No-Operation: _
#ctx: the context object.
#vars: the context variables.
#locale: the context locale.
#request: (only in Web Contexts) the HttpServletRequest object.
#response: (only in Web Contexts) the HttpServletResponse object.
#session: (only in Web Contexts) the HttpSession object.
#servletContext: (only in Web Contexts) the ServletContext object.
Exemplo:
<p th:text="${#locale}"></p>`
#execInfo: information about the template being processed.
#messages: methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
#uris: methods for escaping parts of URLs/URIs
#conversions: methods for executing the configured conversion service (if any).
#dates: methods for java.util.Date objects: formatting, component extraction, etc.
#calendars: analogous to #dates, but for java.util.Calendar objects.
#numbers: methods for formatting numeric objects.
#strings: methods for String objects: contains, startsWith, prepending/appending, etc.
#objects: methods for objects in general.
#bools: methods for boolean evaluation.
#arrays: methods for arrays.
#lists: methods for lists.
#sets: methods for sets.
#maps: methods for maps.
#aggregates: methods for creating aggregates on arrays or collections.
#ids: methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
Exemplo:
model.addAttribute("today", Calendar.getInstance());
<span th:text="${#calendars.format(today,'dd MMMM yyyy')}">13 May 2011</span>`
<table>
<tr>
<th>ID</th>
<th>Nome</th>
<th>Telefone</th>
</tr>
<tr th:each="c : ${convidados}">
<td th:text="${c.id}"></td>
<td th:text="${c.nome}"></td>
<td th:text="${c.telefone}"></td>
</tr>
</table>
Para trabalhar com fragmentos em páginas separadas e importados em um página principal, o Thymeleaf fornece alguns componentes:
th:insert - é o mais simples: ele simplesmente vai inserir o fragmento como o corpo de uma tag na página de destino.
th:replace - substitui a tag da página de destino pelo fragmento.
th:include - é semelhante ao th: insert, mas em vez de inserir o fragmento, ele apenas insere o conteúdo desse fragmento.
th:fragment - define um trecho de html como um fragmento de página.
Vamos criar um fragment: footer.html
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body>
<footer class="layout-footer" th:fragment="rodape">
<div class="container">
<span class="footer-copy">© 2020 Empresa. Todos os direitos reservados.</span>
</div>
</footer>
</body>
</html>
Agora, suponha que temos a página index.html e nela vamos incluir o fragmento de rodapé.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>Thymeleaf</title>
</head>
<body>
<div>
<div>Qualquer outro contéudo aqui</div>
</div>
<div class="container">
<div>O corpo da página poderia estar aqui</div>
</div>
<footer th:replace="footer :: rodape">
<span>O rodapé será inserido aqui!</span>
</footer>
</body>
</html>
Há também um projeto secundário que foi oficializado pelo Thyemeleaf para a inclusão de fragmentos:
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
A primeira instrução que deve ser adicionada as páginas é o namespace: xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout". Com sua inclusão teremos acesso a dois importantes componentes:
layout:fragment - tem como finalidade criar e nomear o fragmento de página, tem um propósito similar ao th:fragment. Porém, ele também deve ser usado para carregar o fragmento na página de destino, em substituição ao th:replace.
layout:decorate - deve ser incluído na tag da página de fragmento. Seu objetivo é informar a página de fragmento qual será a página de destino deste fragmento. Sendo assim, como valor passamos a instrução ~{nome da página de destino}.
Veja agora um exemplo da página cadastro.html
que será usado como um fragmento:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{index}">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
</head>
<body>
<div class="container" layout:fragment="corpo">
<form action="#" method="post">
<!--código omitido -->
</form>
</div>
</body>
</html>
Agora, na página index.html
importamos este fragmento da seguinte forma:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
</head>
<body>
<div>
<div>Qualquer outro contéudo aqui</div>
</div>
<div class="container" layout:fragment="corpo">
<div>O corpo da página poderia estar aqui</div>
</div>
<footer th:replace="footer :: rodape">
<span>O rodapé será inserido aqui!</span>
</footer>
</body>
</html>