인프런 김영한님 스프링부트 강의를 들으면서 타임리프의 기본 문법을 정리하였다.
우선 dependencies 에 추가해 준다.
dependencies{
...
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
...
}
# 서버에서 보낸 데이터를 바로 사용할 때 (th:text 사용)
<li>th:text 사용 <span th:text="${data}"></span></li>
<li>컨텐츠 안에서 직접 출력하기 = [[${data}]]</li>
# 객체 데이터를 접근할 때 (SpringEL 표현식)
# Object # List # Map
${user.username} ${users[0].username} ${userMap['userA'].username}
${user['username']} ${users[0]['username']} ${userMap['userA']['username']}
${user.getUsername()} ${users[0].getUsername()} ${userMap['userA'].getUsername()}
# URL 링크, 파라미터 전송 (th:href)
<a th:href="@{/hello}">basic url</a>
<a th:href="@{/hello(param1=${param1}, param2=${param2})}">>hello query param</a>
<a th:href="@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}">path variable</a>
<a th:href="@{/hello/{param1}(param1=${param1}, param2=${param2})}">path variable + query parameter</a>
# 반복 (th:each)
<tr th:each="user : ${users}">
<td th:text="${user.username}">username</td>
<td th:text="${user.age}">0</td>
</tr>
index : 0부터 시작하는 값
count : 1부터 시작하는 값
size : 전체 사이즈
even , odd : 홀수, 짝수 여부( boolean )
first , last :처음, 마지막 여부( boolean )
current : 현재 객체
# 조건 (th:if, th:unless, th:switch) ( if <-> unless )
# 해당조건이 맞지 않으면 태그 자체를 렌더링하지 않음
<td>
<span th:text="${user.age}">0</span>
<span th:text="'미성년자'" th:if="${user.age lt 20}"></span>
<span th:text="'미성년자'" th:unless="${user.age ge 20}"></span>
</td>
<td th:switch="${user.age}">
<span th:case="10">10살</span>
<span th:case="20">20살</span>
<span th:case="*">기타</span>
</td>
# 블록 (th:block)
# 태그를 여러번 사용해야하는 경우에 사용
<th:block th:each="user : ${users}">
<div>
사용자 이름1 <span th:text="${user.username}"></span>
사용자 나이1 <span th:text="${user.age}"></span>
</div>
<div>
요약 <span th:text="${user.username} + ' / ' + ${user.age}"></span>
</div>
</th:block>
# 자바스크립트 인라인 (th:inline)
# 자바스크립트 안에서 타임리프 사용
<script th:inline="javascript">
var username = [[${user.username}]];
var age = [[${user.age}]];
//자바스크립트 내추럴 템플릿
var username2 = /*[[${user.username}]]*/ "test username";
//객체
var user = [[${user}]];
</script>
이외에도 여러 가지 기능이 있지만 강의를 들으면서 이 정도는 정리해 두면 자주 볼 거 같다는 생각이 들었다.
출처 : 인프런 스프링 MVC 강의
'개발공부 > Spring' 카테고리의 다른 글
스프링 인터셉터 (Interceptor) (0) | 2023.08.03 |
---|---|
필터(Filter) (0) | 2023.08.02 |
데이터 검증 (Validation) (0) | 2023.07.31 |
타임리프에서 스프링부트 메시지 사용하기 (0) | 2023.07.28 |
타임리프 기본 문법 정리 (form 태그) (0) | 2023.07.28 |