its_jh_stroy

[Springboot] thymeleaf로 화면 레이아웃 구성하기 본문

Java

[Springboot] thymeleaf로 화면 레이아웃 구성하기

_J_H_ 2024. 6. 30. 15:42

스프링부트에서 thymeleaf 라이브러리는 웹사이트의 공통된 부분을 하나씩 작성하지 않고, 템플릿 형태를 만들어 개발할 수 있는 기능을 지원한다.

몇 가지 속성을 통해 사이트의 공통 양식을 지정하여 효율적인 화면 개발을 할 수 있다.

페이지는 아래와 같이 templates 폴더에 네 가지 html 파일을 구성할 것이다.

- layoutPage.html

- content.html

- fragments/header.html

- fragments/footer.html

 

의존성 추가

시작 전 아래와 같이 build.gradle 파일에 의존성을 추가한다.

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

 

layoutPage 구성하기

<!DOCTYPE html>
<html
        xmlns:th="http://www.thymeleaf.org"
        xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <title>Layout page</title>
</head>
<body>

<header th:replace="fragments/header :: header"></header>

<section layout:fragment="content">
    <p>Page content</p>
</section>

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

</body>
</html>

 

위 코드를 통해 전체 템플릿이 될 layoutPage 파일에 header, content, footer 영역을 정의하였다.

 

Content 페이지 구현

@Controller
public class HomeController {
    @GetMapping("/")
    public String home() {
        return "content";
    }
}
<!DOCTYPE html>
<html
        xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
        layout:decorate="~{layoutPage.html}">
<head>
  <title>Content page</title>
</head>
<body>

<section layout:fragment="content">
  <p>This is a paragraph from the content page</p>
</section>

</body>
</html>

 

 

layout:decorate 속성으로 사용할 레이아웃 파일을 지정하고, layout:fragment 속성으로 레이아웃 파일에서 사용될 코드를 정의하였다.

 

header와 footer 구성하기

마지막으로 header와 footer 파일이다.

 

header.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<footer th:fragment="header">
    <p>This is header</p>
</footer>
</html>

 

footer.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<footer th:fragment="footer">
    <p>This is footer</p>
</footer>
</html>