Thymeleaf Commands

Published: 2019-08-04, Updated: 2023-01-24

Links

Chamar método estático

[[${@thymeleaf.ThymeleafUtils@analyticsId()}]]
<span th:text="${@thymeleaf.ThymeleafUtils@analyticsId()}"></span>

Incluir scripts

<script th:utext="'window.report=' + *{report}"></script>
<script th:src="@{/assets/js/gerencial-relatorio.js}"></script>

Declarar variável

<div th:with="someVariable=${someValue}">

Imprimir variavel concatenada ao inves de substituir tudo

<h1 th:inline="text" >
	 [[${header.title}]]
	 <small th:text="${header.subtitle}">Subtitle</small>
</h1>

Incluir fragmentos nas paginas

fragments/results.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<div th:fragment="results">
some content
</div>

page.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
	xmlns:layout="http://www.thymeleaf.org"
	layout:decorator="layout/general"
>
<head>
	<title>Home</title>
</head>
<body >
	<div layout:fragment="content" >
		<div th:replace="fragment/results :: results"></div>
	</div>
</body>
</html>

Montando layout / Template

Referências

Forma recomendada

Forma 1 (Só funciona com Spring)

Forma 2

with Thymeleaf 2.1, you can write something like that:

Create the template (for ex. templates/layout.html), and add the th:fragment="page" information in html tag and define the content area with th:include="this :: content" information:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" th:fragment="page">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Test</title>
	</head>
	<body>
		layout page
		<div th:include="this :: content"/>
		layout footer
	</body>
</html>

Now create the page that will include this template adding th:include="templates/layout :: page" in html tag and put your main content inside a div with th:fragment="content"

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	th:include="templates/layout :: page">
	<head>
		<title></title>
	</head>
	<body>
		<div th:fragment="content">
			my page content
		</div>
	</body>
</html>

In layout page you can use this (th:include="this :: content") or suppress this option (th:include=":: content"). It seems like jsf facelets I think.

Concatenar strings

th:text="#{App.Title} + #{user.list}"

If not thymeleaf

<div th:if="${geometry} == null" >
	estah nulo
</div>

Usando as expressions

Dar esse se for nulo

${x}

Nao dar erro se for nulo

#{x}

Ternario

<span th:text="${oae.name == null} ? 'Não Informado' : ${oae.name}" />

Montando um link com query params

<td th:with="oaeClassificationId=${c.oaeClassificationId == null} ? '' :  ${c.oaeClassificationId},classifyLink='?oaeId=' + ${c.oaeId} + '&amp;classificationId=' + ${oaeClassificationId}">
<a th:href="@{/classificacao-oae.html} + ${classifyLink}"
	 th:if="${c.oaeClassificationId != null}"
	 class="btn btn-primary waves-effect waves-light margin-bottom-5"
>Editar</a>

Usando ModelAttribute para mapear um form dentro de uma propriedade

FormTestController.java

@Controller
public class FormTestController {

	@RequestMapping(value = "/form-test-1.jhtml", method = RequestMethod.GET)
	public String formTest1(@ModelAttribute("form1") Form1TestVO form1TestVO, Model model){
		model.addAttribute("form1", new Form1TestVO("Form 1 test"));
		return "form-test-1";
	}
}

form-test-1.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.thymeleaf.org" >
<head>
	<title>Form test 1</title>
</head>
<body >

	<form th:object="${form1}" th:action="@{/form-test-1.jhtml}" >
		<input  th:field="*{name}" />
		<button>Send</button>
	</form>

</body>
</html>

Form1TestVO

public class Form1TestVO {
	private String name;

	public Form1TestVO() {
	}

	public Form1TestVO(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

Setar o nome e valor do campo via thymeleaf

<td class="text-center"><input value="" required="" th:field="*{durableClassificationPoint.mesosStructure}" type="number"  min="1" max="5"/></td>

Imprimir texto sem espacar por exemplo JSON

<script th:utext="${json}"></script>

Deixar um select com valor default prefixado marcado

<select id="executiveProcedureId" th:field="*{executiveProcedureId}" required="" class="form-control">
	<option value=""></option>
	<option th:each="ep : ${procedures}" th:value="${ep.id}" th:text="${ep.description}"></option>
</select>

Deixar option selecionado com o valor que vinher do server

Forma 1

<select name="openChats" class="form-select" id="slcActiveLiveChat" required>
  <option th:selected="${root.openChats} == 1" value="1">Enabled</option>
  <option th:selected="${root.openChats} == 0" value="0">Disabled</option>
</select>

Forma 2

<select id="size">
  <option th:each="size : ${task.complexity}"
    th:value="${size}"
    th:selected="${task.size} == ${size} ? true : false"
    th:text="${size}"></option>
</select>

Chamar classe / metodo java

package com.mageddo.professionals.utils;

import java.time.LocalDate;

public class DateUtils {
	public static int currentYear(){
		return LocalDate.now().getYear();
	}
}
<span class="tm-current-year" th:text="${T(com.mageddo.professionals.utils.DateUtils).currentYear()}"></span>

Escaping

Por default thymeleaf escapa HTML, JSON, etc, para forcar que ele nao esape faça assim

<span th:utext="${someVar}" />
ou
[(${someVar})]

Exemplos de iteração

<tr th:each="c : ${classfifications}">
	<td th:text="*{c.oaeId}"></td>
	<td th:text="*{c.oaeName}"></td>
	<td>
		<span class="label label-info">Ativo</span>
	</td>
	<td>
		<a th:href="@{/gerencial-relatorio.html} + '?oaeId=' + *{c.oaeId}" class="btn btn-primary waves-effect waves-light margin-bottom-5">Gerar Relatório</a>
	</td>
</tr>

Custom parameter / custom attribute

<a th:attr="data-post-id=${post.id}" />

Laravel Commands Atalhos de teclado do Youtube

Comments