Search code examples
htmlspringspring-bootspring-mvcthymeleaf

Thymeleaf fragments not being resolved


So I've trying to use fragments but it seems like there is a problem resolving the fragment itself. I'm guessing it is a fragment resolver issue as the code for the fragment should be right but shouldn't the fragment resolver be auto-configured? Any help is appreciated!

Error

org.thymeleaf.exceptions.TemplateInputException: Error resolving template [fragments/navbar], template might not exist or might not be accessible by any of the configured Template Resolvers (template: "flights-listOneWay" - line 15, col 6)

Main html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet"
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
    integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
    crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.5.1.js"
    integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
    crossorigin="anonymous"></script>
<title>Chrono Airlines</title>
</head>
<body>
<div th:replace="fragments/navbar :: navigation"></div>
----more html below----

Fragment. Placed under resources/fragments/navbar.html

<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <div th:fragment="navigation">
    <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
              <div class="navbar-header">
                <a class="navbar-brand" href="#">Chrono Airlines</a>
              </div>
              <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                  <li class="active"><a href="/">Home</a></li>
                  <li class="active"><a href="/">Login</a></li>
                </ul>
              </div>
              
            </div>
          </div>
          </div>

Solution

  • Inside of the fragment you have to also give it a name. In your case add these 2 lines on top. (Don’t forget to close this new div)

    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <div th:fragment="navigation">
    

    And in the first document replace should be nameOfTheFile::fragmentName

    th:replace="fragments/navbar::navigation"