Spring

Thymeleaf html에서의 문법

YunSeong 2024. 8. 1. 16:37
728x90
반응형

1. Thymeleaf namespace 선언

<html xmlns:th="http://www.thymeleaf.org">
    ...
</html>

다음과 같이 namespace를 선언할 수 있다.

2. 속성 값 바인딩

<!-- html 요소의 텍스트를 설정 -->
<p th:text="${message}"> default text </p>

<!-- 링크 URL을 설정 -->
<a th:href="@{/your/path}"> text </a>

<!-- 이미지 소스 URL을 설정 -->
<img th:scr="@{/path/image.png}"/>

3. 조건문

<!-- 조건이 참일 때만 렌더링 -->
<div th:if="${user != null}"/>

<!-- 조건이 거짓일 때만 렌더링 -->
<div th:unless="${user != null}"/>

4. 반복문

<!-- 컬렉션을 반복하여 html 요소 생성 -->
<ul>
    <li th:each="item : ${items}" th:text="${item}"></li>
</ul>

5. 폼 필드 바인딩

<!-- 폼 필드와 객체 속성을 바인딩 -->
<form th:action="@{/submit}" th:object="${form}" method="post">
    <input type="text" th:field="*{name}"/>
    <textarea th:field="*{description}"></textarea>
    <button type="submit">Submit</button>
</form>

<!-- @ModelAttribute Form form 다음과 같은 parameter로 폼을 보내고 th:object에서 받는다. 또한 form의 맴버 변수인 content를 th:field에서 연결해준다.  -->

6. Fragment

<!-- 현재 요소를 다른 템플릿으로 대체 -->
<div th:replace="[파일명] :: [fragment명]"></div>

<!-- 현재 요소를 다른 템플릿으로 포함 -->
<div th:include="[파일명] :: [fragment명]"></div>

<!-- fragment 지정 -->
<div th:fragment="fragment"></div>

@{} - url을 생성
${} - 변수를 출력
*{} - 폼 필드 바인딩을 정의할 때 사용됨

728x90
반응형

'Spring' 카테고리의 다른 글

JPA Specification Interface  (0) 2024.08.02
Spring JPA의 Entity란?  (0) 2024.08.01
JPA 쿼리 메서드  (0) 2024.07.30
Spring Service, Controller의 차이점  (0) 2024.07.30
Java Package와 Directory의 차이점  (0) 2024.07.30