Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf + Spring Boot: placing html in subfolders

By default, Thymeleaf needs all the html files to be present in scr/main/java/resources/templates. In order not to create a mess in templates folder I need to create different subloders there. The problem is that html files placed there never get resolved. Example is below.

Structure:

project structure

IndexController:

@Controller
public class IndexController {
    @GetMapping(value = "/")
    public String index() {
        return "index";
    }
}

default template:

<!DOCTYPE html>
<html lang="en"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <meta charset="UTF-8"/>
    <title>Default template</title>
</head>
<body>

<section id="site-content" layout:fragment="content"></section>

</body>
</html>

index:

<!DOCTYPE html>
<html lang="en"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorator="default">
<head>
    <meta charset="UTF-8"/>
    <title>Index</title>
</head>
<body>

<div layout:fragment="content">
    <div>
        This is index page
    </div>

    <a href="subfolder/page.html">Page</a>
</div>

</body>
</html>

page in the subfolder:

<!DOCTYPE html>
<html lang="en"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorator="default">
<head>
    <meta charset="UTF-8">
    <title>Page</title>
</head>
<body>

<div layout:fragment="content">
    This is a page in the subfolder
</div>

</body>
</html>

When I open index page and click the link to the page.html, I get this:

error

What I did wrong?

like image 536
sva605 Avatar asked Oct 27 '25 14:10

sva605


1 Answers

You have no controller mapping for /subfolder/page.html, this is not how Thymeleaf and Spring work.

You can't easily reference plain HTML files, as they aren't technically stored there. You have to reference an endpoint defined within Spring which will then select the HTML file to be rendered, like so:

@Controller
public class IndexController {
    @GetMapping(value = "/subfolder/page")
    public String index() {
        return "subfolder/page";
    }
}

and create your link like this:

<a href="subfolder/page">Page</a>
like image 179
N4zroth Avatar answered Oct 29 '25 12:10

N4zroth