[ Frontend ]/JSP_Thymeleaf

[Thymeleaf] 기본 문법 (연산, 반복, if, 블록)

HSRyuuu 2023. 5. 4. 00:30

연산

1. 산술 연산

<li><span th:text="10 + 2"></span></li> <!--12-->
<li><span th:text="10 % 2 == 0"></span></li> <!--true-->

2. 비교 연산

<li><span th:text="1 &gt; 10"></span></li> <!--false-->
<li><span th:text="1 gt 10"></span></li> <!--false-->
<li><span th:text="1 >= 10"></span></li> <!--false-->
<li><span th:text="1 ge 10"></span></li> <!--false-->
<li><span th:text="1 == 10"></span></li> <!--false-->
<li><span th:text="1 != 10"></span></li> <!--true-->
  • &gt; , gt (greater) = >
  • ge (greater or equal) = >=
  • lt (little) = <
  • le (little or equal) = <=와 같음
  • eq (equal) = =
  • ne (not equal) =!=

3. 조건식

  • (...)? A : B  : () 안이 true인지 false인지에 따라 각각 ' : '의 왼쪽, 오른쪽 반환
  • true일 때 : 왼쪽 반환
  • false일 때 : 오른쪽 반환
<li><span th:text="(10 % 2 == 0)?'짝수':'홀수'"></span></li> <!--짝수-->

4. Elvis 연산자

${data}?:"..."

  • 값이 존재하면 ${…} 값을 출력하고, null일 경우 :... 을 출력
String data = “Spring”;
String nullData = null;
<li><span th:text="${data}?: '데이터가없습니다.'"></span></li>
<li><span th:text="${nullData}?:'데이터가 없습니다.'"></span></li>

(출력)

Spring

데이터가 없습니다.


5. No-Operation

${data}?: _

  • 값이 존재하면 ${…} 값을 출력하고, null일 경우 : 타임리프가 없는 것처럼 동작한다.
  • 아래에서는 기본이 “데이터가 없습니다.” 문자열이다.
String data = “Spring”;
String nullData = null;
<li><span th:text="${data}?: _">데이터가 없습니다.</span></li>
<li><span th:text="${nullData}?: _">데이터가없습니다.</span></li>
  • 첫 번째 줄의 경우 data가 존재하므로 Spring을 출력한다.
  • 두 번째 줄은 data가 존재하지 않으므로 th:text="${nullData}?: _"이 없는 것처럼 동작한다.

반복

1. 반복 출력 - th:each

<tr th:each="user : ${users}"> (code) </tr>
  • 반복은 th:each를 사용한다. 이렇게 하면 반복문 안에서 user 변수를 사용할 수 있다.
  • ${users}의 컬렉션의 수만큼 <tr> 내부의 (code)가 하위 태그를 포함해서 생성된다.

반복 예제

<tr th:each="user : ${users}">
  • 반복 시 ${users}의 값을 하나씩 꺼내서 왼쪽 변수 user에 담아서 태그를 반복 실행한다.
  • th:eachjava.util.Iterable , java.util.Enumeration을 구현한 모든 객체에서 사용 가능하다.
  • Map도 사용할 수 있는데 이 경우 변수에 담기는 값은 Map.Entry이다.


2. 반복 상태 표현

<tr th:each="user, userStat : ${users}">
  • 기본과 똑같이 user${users}가 하나씩 담긴다.
  • userStat은 반복의 상태를 담는다

반복 상태를 표현하는 변수들

  • index : 0부터 시작하는 값
  • count : 1부터 시작하는 값
  • size : 전체 사이즈
  • even, odd : 홀수, 짝수 여부 (boolean)
  • first, last : 처음, 마지막 여부 (boolean)
  • current : 현재 객체

<tr th:each="user: ${users}">userStat을 생략할 수 있다.

  • 생략하면 해당 값을 가져올 때, 단일 객체 이름(user) + Stat을 사용한다.
<table border="1">
    <tr>
        <th>count</th>
        <th>username</th>
        <th>age</th>
        <th>etc</th>
    </tr>
    <tr th:each="user, userStat : ${users}">
        <td th:text="${userStat.count}">username</td>
        <td th:text="${user.username}">username</td>
        <td th:text="${user.age}">0</td>
        <td>
            index = <span th:text="${userStat.index}"></span>
            count = <span th:text="${userStat.count}"></span>
            size = <span th:text="${userStat.size}"></span>
            even? = <span th:text="${userStat.even}"></span>
            odd? = <span th:text="${userStat.odd}"></span>
            first? = <span th:text="${userStat.first}"></span>
            last? = <span th:text="${userStat.last}"></span>
            current = <span th:text="${userStat.current}"></span>
        </td>
    </tr>
</table>


조건부 평가 if, unless, switch

1. if, unless

<span th:text="'미성년자'" th:if="${user.age lt 20}"></span>
  • lt = <
  • ge = >=

th:if를 사용했을 때, 타임리프는 해당 조건이 맞지 않으면 태그 자체를 렌더링 하지 않는다.

만약 조건이 false 인 경우 <span>... <span> 자체를 렌더링 되지 않고 사라진다.

 

(ex) 아래 두 개는 같은 조건이다.

if : user.age < 20 일 때 출력
unless : user.age >= 20 이 아닐 때 출력

만약 user.age가 18이면 둘 다 출력되고, 23이면 둘 다 출력되지 않을 것이다.

<span th:text="'미성년자'" th:if="${user.age lt 20}"></span>
<span th:text="'미성년자'" th:unless="${user.age ge 20}"></span>

2. switch

th:switch , th:case

<td th:switch="${user.age}">
    <span th:case="10">10살</span>
    <span th:case="20">20살</span>
    <span th:case="*">기타</span>
</td>

th:case="*" : default


블록

th:block 은 HTML 태그가 아닌 타임리프의 유일한 자체 태그다.

  • 여러 개의 태그를 한 번에 반복문을 사용해야 할 때 사용한다.
<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>

출력

사용자 이름1 UserA 사용자 나이1 10
요약 UserA / 10
사용자 이름1 UserB 사용자 나이1 20
요약 UserB / 20
사용자 이름1 UserC 사용자 나이1 30
요약 UserC / 30

 


(참고) 김영한 님 인프런 Spring MVC-2
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-2
반응형