Spring Boot/STUDY

[Spring Boot] JPA 프로젝트 - Thymeleaf로 레이아웃 템플릿 생성

코맹 2024. 6. 19. 10:38

 

  • html 코드를 편하게 쓰기 위해 html5-skelton 설치

 

/templates/layout.html 생성

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Backboard Website</title>
    <!-- <link rel="icon" type="image/x-icon" href="./assets/favicon.ico" /> -->
    <link rel="stylesheet" type="text/css" th:href="@{/bootstrap.min.css}">
    <!-- 웹사이트용 CSS -->
    <link rel="stylesheet" type="text/css" th:href="@{/main.css}">
    <!-- Favicon 탭에 들어가는 아이콘 -->
    <link rel="icon" href="https://getbootstrap.com//docs/5.3/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png">
    <link rel="icon" href="https://getbootstrap.com//docs/5.3/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png">
  </head>

  <body>
    <!-- 레이아웃에 적용될 하위 페이지 위치 -->
     <th:block layout:fragment="main-content">

     </th:block>
    <script th:src="@{/bootstrap.min.js}"></script>
    <!-- 각 페이지마다 추가되어야 할 자바스크립트 영역 -->
     <th:block layout:fragment="sub-script">

     </th:block>
  </body>
</html>

 

/templates/board/list.html 코드 수정

<!doctype html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org" layout:decorate="~{layout}">
    <div layout:fragment="content" class="container my-3">
      <table class="table table-light table-striped">
        <thead class="table-dark">
          <tr>
            <th>번호</th>
            <th>제목</th>
            <th>작성일</th>
          </tr>
        </thead>
        <tbody>
          <tr th:each="board, loop: ${boardList}">
             <td th:text="${loop.count}"></td>
             <td>
              <a th:href="@{|/board/detail/${board.bno}|}" th:text="${board.title}"></a>
             </td>
            <td th:text="${#temporals.format(board.createDate, 'yyyy-MM-dd HH:mm')}"></td>
          </tr>
        </tbody>
      </table>
    </div>
</html>
  • <html lang="ko" xmlns:th="http://www.thymeleaf.org" layout:decorate="~{layout}"> 추가
  • <div layout:fragment="content" class="container my-3">  추가
  • 이후 <head><body> 태그 모두 삭제
  • detail.html도 동일하게 적용시키면 됨

 

💥 위 코드를 추가해줬는데 Bootstrap이 적용되지 않는 문제 발생

  • build.gradle에 아래 dependency를 추가하니 적용되었다!!
    • implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'