반응형
Thymeleaf에서 th:if는 조건부로 HTML 요소를 렌더링 하는 데 사용되는 속성입니다. 이 속성을 사용하면 특정 조건이 충족될 때만 HTML 요소를 표시하거나 숨길 수 있습니다.
th:if는 일반적으로 Thymeleaf 템플릿 엔진과 함께 사용되며, 다음과 같은 방식으로 사용됩니다:
<div th:if="${condition}">
<!-- 조건이 true일 때 표시될 내용 -->
</div>
여기서 ${condition}은 평가될 조건을 나타내며, 조건이 true일 때 내부의 HTML 요소가 렌더링 됩니다.
다음은 th:if를 사용한 간단한 예제입니다:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf Example</title>
</head>
<body>
<div th:if="${user.isAdmin}">
<p>Welcome Admin!</p>
</div>
<div th:if="${not user.isAdmin}">
<p>Welcome User!</p>
</div>
</body>
</html>
이 예제에서는 user.isAdmin이라는 조건에 따라 관리자 여부를 확인하고, 해당하는 메시지를 출력합니다.
또 다른 예제로는 리스트의 요소를 순회하면서 특정 조건에 맞는 요소만 표시하는 경우가 있습니다:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf Example</title>
</head>
<body>
<ul>
<li th:each="item : ${items}" th:if="${item.price > 100}">
<span th:text="${item.name}"></span> - <span th:text="${item.price}"></span>
</li>
</ul>
</body>
</html>
이 예제에서는 items라는 리스트를 순회하면서 각 요소의 가격이 100보다 큰 경우에만 리스트 아이템을 표시합니다.
이렇게 th:if를 사용하면 템플릿에서 조건부로 HTML을 렌더링 할 수 있어서 동적인 페이지를 만드는 데 유용합니다.
반응형
'Framework > Springboot' 카테고리의 다른 글
[Springboot] @ToString.Exclude, @ToString(exclude =" ") 정리 및 오류 (0) | 2024.06.12 |
---|---|
[Springboot] Session이란? (0) | 2024.05.30 |
[Springboot] Scope란? (0) | 2024.05.30 |
[Springboot] DB설정 / JPA (0) | 2024.05.09 |
[Springboot] Controller (get / post) (0) | 2024.05.09 |