참치코더의 꿈 메모장

Spring / Thymeleaf 핵심 문법 미니 정리 본문

Spring

Spring / Thymeleaf 핵심 문법 미니 정리

참치깡 2025. 9. 7. 22:18
728x90

 

Thymeleaf 핵심 문법 정리

1. 변수 출력

컨트롤러에서 전달된 모델 데이터를 출력합니다.

<p th:text="${msg}">Hello World</p>

기본값 지정:

<p th:text="${msg} ?: '기본 메시지'"></p>

2. 반복문

리스트나 배열을 반복 출력할 수 있습니다.

<ul>
  <li th:each="item : ${list}" th:text="${item}">샘플</li>
</ul>

인덱스 사용:

<li th:each="item, iterStat : ${list}" th:text="${iterStat.index + 1} + ' : ' + ${item}"></li>

3. 조건문

<p th:if="${user != null}">로그인 상태</p>
<p th:unless="${user != null}">로그인 필요</p>

4. 지역 변수 선언

<div th:with="num1=10, num2=20">
  <p th:text="${num1 + num2}"></p>
</div>

5. 자바스크립트 Inlining

<script th:inline="javascript">
var msg = [[${msg}]];
var arr = [[${list}]];
console.log(msg, arr);
</script>

6. 속성 바인딩

<img th:src="@{/images/logo.png}" alt="로고">
<a th:href="@{/user/{id}(id=${user.id})}">프로필</a>

7. Layout Dialect

레이아웃 템플릿 상속과 fragment 덮어쓰기 예제입니다.

<!-- layout.html -->
<body>
  <div layout:fragment="content">기본 콘텐츠</div>
  <script layout:fragment="script"></script>
</body>

<!-- 자식 페이지 -->
<html layout:decorate="~{layout/layout.html}" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<body>
  <div layout:fragment="content">자식 페이지 내용</div>
  <script layout:fragment="script" th:inline="javascript">
    const list = [[${list}]];
    console.log(list);
  </script>
</body>
</html>

8. 주의 사항

  • HTML 태그 중복 주의 (특히 <html> 한 번만)
  • JS inlining 시 [[...]] 사용 필수
  • Layout Dialect fragment 이름 일치 필요
  • 모델 이름 대소문자 구분
728x90
Comments