Issue
I am trying to learn Thymeleaf and when using th:fragment and th:replace or th:insert, nothing is displayed on the page. This is in intellij Idea using the spring boot framework.
What I've tried:
Changing routing on th:insert (ex. th:insert="fragments/test::test">)
Trying different code in the fragment
Changing test.html to include / not include
"xmlns:th="http://www.thymeleaf.org""
Stopping / restarting Apache Tomcat for every single change I make
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>SC2Hub</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SC2Hub</name>
<description>SC2Hub</description>
<properties>
<java.version>18</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
index.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Title</title>
</head>
<body>
<div th:insert="test::test"></div>
<div th:replace="test::test"></div>
</body>
</html>
test.html:
<div th:fragment="test">
<h1>Hello from the fragment!</h1>
</div>
File structure:
project
--src
----resources
------static
--------index.html
------templates
--------fragments
----------test.html
Solution
From the given code I see 2 issues. The first is that your index.html is not inside the templates folder, all files used by thymeleaf should be inside this folder unless you've overriden the default value of where thymeleaf looks for files.
After that as mentioned by @andrewJames fragment calls should be relative to the thymeleaf source folder (by default src/main/resources/templates
) and in your case that would be <div th:replace="fragments/test::test"></div>
Answered By - Ralan
Answer Checked By - Pedro (JavaFixing Volunteer)