Java Framework/Spring Boot

[Spring Boot] Thymeleaf 속성

annovation 2024. 12. 16. 13:05

Thymeleaf

https://annovation.tistory.com/102


주요 속성

1. 조건문 th:if

조건이 참(true)일 때 요소를 표시

<p th:if="${question != null}">Question exists!</p>

 

  • <p> 태그
    • HTML에서 문단(paragraph)을 나타내는 태그입니다.
    • 이 안에 "Question exists!"라는 텍스트가 출력됩니다.
  • th:if="${question != null}"
    • Thymeleaf의 조건문 속성입니다.
    • question이라는 서버에서 전달된 데이터가 null이 아닌 경우(true)에만 이 <p> 태그가 렌더링됩니다.
  • "Question exists!"
    • 조건이 만족되었을 때, 즉 question != null인 경우 사용자에게 보여질 텍스트입니다.

 

2. 조건문 th:unless

조건이 거짓(false)일 때 요소를 표시

<p th:unless="${question == null}">Question exists!</p>

 

  • 위 코드는 question이 null이 아닌 경우에 <p> 태그를 표시합니다.

3. 반복문 th:each

자바의 for-each 문과 유사하며, 리스트 데이터를 반복 처리할 때 사용됩니다.

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

 

  • questionList의 각 요소를 question 변수에 대입하여 반복 실행
  • question.subject와 question.createDate 값을 각각 <td> 태그에 출력

4. 반복문 loop

두 번째 변수 loop을 추가하여 루프 상태를 확인할 수 있습니다.

<tr th:each="question, loop : ${questionList}">
    <td th:text="${loop.index}"></td> <!-- 0부터 시작하는 반복 순서 -->
    <td th:text="${loop.count}"></td> <!-- 1부터 시작하는 반복 순서 -->
    <td th:text="${loop.first}"></td> <!-- 첫 번째 반복이면 true -->
    <td th:text="${loop.last}"></td> <!-- 마지막 반복이면 true -->
    <td th:text="${question.subject}"></td>
</tr>
  • loop.index : 반복 순서 (0부터 시작)
  • loop.count : 반복 순서 (1부터 시작)
  • loop.first : 첫 번째 반복이면 true
  • loop.last : 마지막 반복이면 true
  • loop.odd : 현재 반복이 홀수 순서이면 true
  • loop.even : 현재 반복이 짝수 순서이면 true

5. 텍스트 출력 th:text

서버 데이터를 HTML 요소의 텍스트로 출력할 수 있습니다.

<p th:text="${question.subject}">Default text</p>
  • question.subject 값이 출력됩니다.
  • 데이터가 없으면 기본값으로 설정된 "Default text"는 표시되지 않습니다.

6. 텍스트 출력 [[ ]]

[[  ]]를 사용하여 HTML 요소 안에서도 데이터를 출력할 수 있습니다.

<tr th:each="question : ${questionList}">
    <td>[[${question.subject}]]</td>
    <td>[[${question.createDate}]]</td>
</tr>
  • 대괄호 표기법은 HTML 구조를 유지하면서 데이터를 동적으로 삽입할 수 있어 가독성이 높습니다.

7. URL 연결 th:href

(1) 링크(URL)를 동적(고정)으로 생성하기 위해 사용합니다.

<a th:href="@{/path}">Link Text</a>

 

(2) URL에서 문자열과 변수를 함께 사용할 때는 반드시 |로 감싸야 합니다.

<a th:href="@{|/path/${variable}|}">Link</a>

요약

속성 역할 예시
th:if 조건이 true일 때 요소를 표시 <p th:if="${data != null}"></p>
th:unless 조건이 false일 때 요소를 표시 <p th:unless="${data == null}"></p>
th:each 반복문 처리 <tr th:each="item : ${items}"></tr>
th:text 텍스트 값을 동적으로 출력 <p th:text="${item.name}"></p>
[[ ]] HTML 구조를 유지하며 데이터 삽입 <p>[[${item.name}]]</p>
th:href 링크(URL)를 연결하여 페이지 간 이동 <a th:href="@{/path}"></a>

출처

OpenAI ChatGPT (https://openai.com)

2024 프로그래머스 백엔드 데브코스 3기 4회차 수업

반응형