반복문으로 list에 저장된 값을 HTML에서도 부를 수 있다는 강점이 있음.

 

<tr th:each="user : ${users}">

구조는 java의 향상된 for 문과 얼추 비슷하다.  user(임의 변수 지정) 에 {users}(자바의 리스트가 담긴 변수) 를 꺼내서 반복해!

 

처리가능한 반복조건은 ,Iterable, Enum,Map, 등등 다양하다.

발췌 : https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#using-theach

<tr>
    <th>이름</th>
    <th>나이</th>
</tr>
//연속된 데이터를 불러올 수 있다. 
<tr th:each="user : ${users}">
    <td th:text="${user.username}">username</td>
    <td th:text="${user.age}">0</td>
</tr>

위와 같이 'user.username' 과 'uer.age' 한번 작성했지만, 아래 코드와 같이 실행결과는 user ,A,B,C 모두를 불러왔다. 

<tr>
    <th>이름</th>
    <th>나이</th>
</tr>
<tr>
    <td>userA</td>
    <td>10</td>
</tr>
<tr>
    <td>userB</td>
    <td>20</td>
</tr>
<tr>
    <td>userC</td>
    <td>30</td>
</tr>

 

 

 

 


 

조건문

<!-- user.age를 가져와서 출력하되 없으면 출력하지않음 -->
<span th:text="${user.age}">0</span>

<!-- user.age 가 20보다 "<"작으면(lt='<') 미성년자를 찍어주고, 조건이 false가 되면
   해당 태그를 아예 없는셈 친다. -->
<span th:text="'미성년자'" th:if="${user.age lt 20}">성인</span>

<!-- user.age 가 20보다 ">" 크면(ge='>') 해당 태그를 없는셈 쳐버리고, 조건이 false가 되면
   즉 , 작으면 미성년자를 찍어준다. -->
<span th:text="'미성년자'" th:unless="${user.age ge 20}">성인</span>

태그 가운데, if, unless 로 작업된다.

 

그래서 만약 나이가 20세라 가정하면 

20
(if false → 출력 안 됨)
(unless false → 출력 안 됨)

 

나이가 15세라 가정하면

15
미성년자
미성년자

 

요래 출력된다. 

 

참고로 연산자는 아래와 같음

lt less than <
le less or equal <=
gt greater than >
ge greater or equal >=
eq equal ==
ne not equal !=

 

+ Recent posts