Thymeleaf es un motor de plantillas que se integra muy bien con el Spring Framework, especialmente con Spring MVC y Spring Boot. A continuación, te presento cómo configurar Thymeleaf en una aplicación Spring, y algunos ejemplos de uso.
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
src/main/resources/templates
.
Por ejemplo, puedes crear un archivo index.html
en esta carpeta.
index.html
:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("titulo", "Página de Inicio");
return "index"; // Retorna la plantilla "index.html"
}
}
index.html
:
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<title th:text="${titulo}">Título por Defecto</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" />
</head>
<body>
<h1 class="text-4xl font-bold text-blue-500" th:text="${titulo}">Título por Defecto</h1>
<p>¡Bienvenido a la aplicación Thymeleaf con Spring!</p>
</body>
</html>
mvn spring-boot:run
http://localhost:8080/
. Deberías ver la página de inicio con el título que definiste en el controlador.