본문 바로가기
Java/Spring Boot

[SpringBoot] Thymeleaf

by curious week 2024. 12. 25.

먼저, thymeleaf를 사용하기 위해서는 build.gradle에 추가한다.

// build.gradle
dependencies {
	//	thymeleaf
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
}

resources 폴더에 templates 폴더를 추가하고 이름.html 파일을 만들면 사용준비가 완료된다. 


th: 가 붙은 부분은 Java코드와 연결된다. Model 객체에 저장한 이름으로 읽을 수 있다.

<th:block th:if="${questionList != null}">
    <table>
        <thead>
        <tr>
            <th>제목</th>
            <th>작성일시</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="question : ${questionList}">
            <td th:text="${question.subject}"></td>
            <td th:text="${question.createDate}"></td>
        </tr>
        </tbody>
    </table>
</th:block>

th:block: 태그가 따로 없을 때 블록을 사용

th:each="변수 : ${JavaList}": List의 데이터를 하나씩 변수에 대입 후 List의 length만큼 반복한다. java의 for each와 유사하다.

th:each="question, loop : ${questionList}"

이처럼 사용가능한데,  jsp(jstl)의 c:forEach 옵션처럼 조건을 정할 수 있다.

더보기

loop 내 사용

loop.index: 루프의 순서(루프의 반복 순서, 0부터 1씩 증가)

loop.count: 루프의 순서(루프의 반복 순서, 1부터 1씩 증가)

loop.size: 반복 객체의 요소 개수(예를 들어 questionList의 요소 개수)

loop.first: 루프의 첫 번째 순서인 경우 true

loop.last: 루프의 마지막 순서인 경우 true

loop.odd: 루프의 홀수 번째 순서인 경우 true

loop.even: 루프의 짝수 번째 순서인 경우 true

loop.current: 현재 대입된 객체(여기서는 question과 동일)

th:text="${변수.속성}": 해당 요소의 텍스트값을 출력한다.

th:text 대신, 대괄호[[]]를 사용하여 직접 출력할 수도 있다.

<tr th:each="question : ${questionList}">
    <td>[[${question.subject}]]</td>
    <td>[[${question.createDate}]]</td>
</tr>

th:href: URL은 반드시 @{  } 문자 사이에 입력

<td>
    <a th:href="@{|/question/detail/${question.id}|}" th:text="${question.subject}"></a>
</td>

좌우에 | 없이 사용하면 오류가 발생

th:action: form 태그 내부 action 속성

<form th:action="@{|/answer/create/${question.id}|}" method="post"></form>

#temporals.format: #temporals.format(날짜 객체, 날짜 포맷)와 같이 사용하는데, 날짜 객체를 날짜 포맷에 맞게 변환

<td th:text="${#temporals.format(question.createDate, 'yyyy-MM-dd HH:mm')}"></td>

xmlns:layout

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <meta charset="UTF-8">
    <title>layout</title>
    <!-- 각 페이지의 script -->
    <th:block layout:fragment="script"></th:block>
    <!-- 각 페이지의 css -->
    <th:block layout:fragment="css"></th:block>
</head>
<body>
    <div th:replace="fragments/header::header"></div>
    <div layout:fragment="content" class="content"></div>
    <div th:replace="fragments/footer::footer"></div>
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http//www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout}">
    <div layout:fragment="content">
       content
    </div>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <div th:fragment="header">
        header
    </div>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <div th:fragment="footer">
        footer 영역입니다.
    </div>
</html>