프로그래밍 언어/Thymeleaf

Thymeleaf 레이아웃 설정

이로률 2025. 2. 28. 17:33

Thymeleaf
서버 사이드 Java 템플릿 엔진.
HTML, XML, JavaScript, CSS 등과 같은 웹 페이지를 생성하는 데 사용
자바 코드와 함께 사용되는 것이 아니라 HTML과 같은 템플릿 파일에 태그를 추가하여 사용

1. head

-include-head.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head th:fragment="head">
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
        <meta name="description" content="" />
        <meta name="author" content="" />
        <title>title</title>
        <!-- Core theme CSS (includes Bootstrap)-->
        <link href="css/styles.css" rel="stylesheet" />
    </head>
</html>

2. script

-include-script.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <th:block th:fragment="script">
        <!-- Bootstrap core JS-->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
        <!-- Core theme JS-->
        <script src="js/scripts.js"></script>
    </th:block>
</html>
  • th:fragment="레이아웃명" : 블록 정의
  • th:block : 단순히 블록 요소를 표시

3. Layout

1) header

-header.html

  • header는 body 안에 위치. header로 태그
  • 여기서 중요한 헤더(header)에 변수 추가. 페이지마다 제목 변경 방법
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <body>
      <header th:fragment="레이아웃명(변수명1, 변수명2)">
          <h1 th:text="${변수명1}"></h1> 
          <p th:text="${변수명2}"></p>
      </header>
    </body>
</html>
  • ex) th:fragment="header(h1, p)"

-index.html

  • th:replace="header::레이아웃명(변수명1='변수', 변수명2='변수')"
  • 여기서 layout/header로 한 이유는 header.html이 layout폴더에 있어서 경로 설정하였다.
  • 만약 변수명1은 설정해주고 싶고 변수명2는 쓰고 싶지 않다면,
    변수명1='변수', 변수명2='' 로 설정 해줘야 한다.  (변수명2를 쓰지 않으면 오류 발생)
  • <body> <!-- Header--> <header th:replace="layout/header::header(h1='두번째 페이지', p='') "> </header> ...

2) footer

-footer.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <footer class="bg-light py-5 mt-auto" th:fragment="footer" > 
        <div class="small text-center text-muted">Copyright &copy; Website 2023</div>
    </footer>
</html>

 

-index.html

<footer th:replace="layout/footer::footer"></footer>

 

4. index.html 전체 코드

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"> 
    <!-- head -->
    <head th:block th:include="common/include-head::head"></head>
    <body>
        <!-- header -->
        <header th:replace="layout/header::header(h1='두번째 페이지', p='') "></header>
        <!-- section -->
        ...
        <!-- Footer -->
        <footer th:replace="layout/footer::footer"></footer>
        <!-- script -->
        <th:block th:insert="common/include-script::script"></th:block>
    </body>
</html>
  • "th:insert": 지정된 템플릿 파일의 내용을 현재 템플릿 파일의 지정된 위치에 삽입
  • "th:include": 지정된 템플릿 파일을 현재 페이지에 포함
  • "th:replace": 지정된 템플릿 파일의 내용으로 현재 요소를 대체