728x90
반응형

이 글은 Thymeleaf 3.0 버전 기준으로 작성되었습니다.

 

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

 

Tutorial: Using Thymeleaf

1 Introducing Thymeleaf 1.1 What is Thymeleaf? Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. The main goal of Thymeleaf is to provide a

www.thymeleaf.org

 

 

 

 

현재 회사 프로젝트에서 Thymeleaf 로 JSP 를 대신해 화면을 구현하고 있습니다.

 

Tiles 처럼 layout 을 만들어서 진행하려고 찾고 진행해보려고 찾아보니 thymeleaf-layout-dialect 를 사용하여 구현하는 글이 많았습니다.

 

gradle 기준 implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect' 의존성 주입을 받아 진행하였습니다.

 

그런데 아무리 해봐도 실행되지 않았습니다.

 

찾아보니 3.0 버전에선 사용이 불가능하다고 하고. 그래도 기존에 돌아가던 코드를 깃헙에서 받아 실행해보았지만 역시 안되네요.

 

그래서 그냥 Thymeleaf 3.0 문서를 보고 구현해보았습니다.

 

 

 

 

 

layout 구현부 입니다.

 

th:fragment="layout(title, content)" 이 부분이 상속을 받을수 있게 해줍니다.

 

fragment 를 생성하면서 함수 인자로 title 과 content 를 받고 있습니다.

 

<title th:replace="${title}">Layout Title</title> 변수를 출력하는 코드로 동적 title 사용이 가능합니다.

 

<div th:replace="${content}"></div> 동적으로 content 를 출력하는 코드 입니다.

 

<!DOCTYPE html>
<html th:fragment="layout(title, content)" xmlns:th="http://www.thymeleaf.org">
<head>
    <title th:replace="${title}">Layout Title</title>
</head>

<body>

    <h1>Layout H1</h1>

    <div th:replace="${content}">

        <p>Layout content</p>

    </div>

    <footer>
        Layout footer
    </footer>

</body>
</html>

 

 

 

 

 

 

content 에 들어갈 html 입니다.

 

html 태그에 th:replace="~{layoutFile :: layout(~{::title}, ~{::section})}" 이런식으로 layoutFile 파일을 선택하고 :: 구분자를 넣어주고 layout() 함수를 호출하는 방식입니다.

 

~{title} title 태그를 주입받습니다.

 

~{section} section 태그를 주입받습니다.

 

두개다 역시 head 나 body 어떤 태그를 사용할 수 있습니다.

 

<!DOCTYPE html>
<html th:replace="~{layoutFile :: layout(~{::title}, ~{::section})}">
<head>
    <title>Page Title</title>
</head>
<body>

<section>

    <p>Page content</p>

    <div>Included on page</div>

</section>
</body>

 

 

 

 

 

 

이대로 실행하면 layout 이 정해진 html 의 content 부분에 section 태그 내용들이 보일것 입니다.

 

툴에 따라 다르지만 IntelliJ 에서 빨간 밑줄이 나오지만 문제없이 돌아갑니다.

 

eclipse 는 빨간줄이 나오지는 않습니다.

 

이 layout 구현을 하려고 Thymeleaf 2.x 대로 내려가려고 했지만 더 가볍게 사용이 가능하니 Thymeleaf 3.x 를 그대로 사용하는걸 추천드립니다.

 

728x90
반응형

+ Recent posts