Thymeleaf layout 적용하기

CHEESE·2022년 7월 6일
0

Thymeleaf

  • 서버 사이드 템플릿 엔진
  • Controller가 전달하는 데이터를 이용하여 동적으로 화면을 구성할 수 있게 해주는 역할
  • HTML의 Attribute를 기반으로 작동되기 때문에 기존 HTML 구조를 건드리지 않는다.
  • th:속성 형식을 통해 값을 치환해주는 방법이 적용된다.
  • Spring에서 공식적으로 Thymeleaf 사용을 권장하고 있다.

layout

고정 영역이 들어가는 웹에서 각각의 page 마다 영역(header, footer 등) 코드를 넣는 것은 비효율적이다.
반복되는 코드를 줄이기 위해 layout을 사용해보자.

thymeleaf 사용 설정

build.gradle

implementation ('nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect')
implementation 'org.springframework.boot:spring-boot-starter-web'

application.properties

# thymeleaf 참조 경로
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

# thymeleaf에 대한 캐시를 남기지 않는다. cache=false 설정(운영시는 true)
spring.thymeleaf.cache=false
# templates 디렉토리에 파일이 있는지 없는지 체크, 없으면 에러를 발생시킨다.
spring.thymeleaf.check-template-location=true

header.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<header th:fragment="headerFragment">
    <nav>
        <div>
            <a href="/">HOME</a>
        </div>
    </nav>
</header>
</html>

footer.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<footer th:fragment="footerFragment">
    <div>
        <p>Copyright &copy; TEST 2022</p>
    </div>
</footer>
</html>

layout.html

<!DOCTYPE html>
<html lang="ko"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
</head>
<body>
  	<!-- th:replace 속성에는 [파일위치]::[th:fragment 속성 값] 순으로 기재한다. -->
    <th:block th:replace="/fragments/header::headerFragment"></th:block>
  	<!-- 동적으로 바뀌는 부분 -->
  	<!-- html내 layout:fragment 속성 값을 맞추면 된다. -->
    <div layout:fragment="content"></div>
    <th:block th:replace="/fragments/footer::footerFragment"></th:block>
</body>
</html>

0개의 댓글