카테고리 없음

타임리프 기본 기능 알아보기 - 2 - 경험을 기록하는

여행하는 개발자(SOO) 2024. 6. 13. 22:52
728x90

연산

주의사항

<> <= >= 같은 비교 연산의 경우 주의해서 사용해야 한다.
gt, lt, ge 같은 문자로 사용하는 경우 문자 그대로 출력이 될 수 있다.

 

기본적으로 사칙연산의 경우 다른 프로그래밍 언어와 똑같다.

 

Elvis 연산: 삼항연산자의 편의 버전
?:

  • <span th:text="${data} ?: '데이터 없음.'"></span> --> 데이터가 있다면 data가, 없다면 데이터 없음 이 출력된다.

No-Operation
_ (언더바) : 타임리프가 실행되지 않는 것처럼 동작한다.

  • <span th:text="${nullData} ?: _">데이터 없음</span> --> 데이터가 있다면 data를 출력하고, 없다면 <span>안에 있는 데이터 없음을 출력한다.

속성 값 설정

th:* 같은 타임리프의 태그 속성

HTML태그 내에서 th:*을 통해서 속성을 지정하고 기존의 태그 속성을 대체한다.

BasicController

@GetMapping("/attribute")  
public String attribute(Model model) {  
    return "basic/attribute";  
}

templates/basic/attribute.html

<!DOCTYPE html>  
<html xmlns:th="http://www.thymeleaf.org">  
<head>  
<meta charset="UTF-8">  
<title>Title</title>  
</head>  
<body>  
<h1>속성 설정</h1>  
<input type="text" name="mock" th:name="userA"/>  
<h1>속성 추가</h1>  
- th:attrappend = <input type="text" class="text" th:attrappend="class='large'"/><br/>  
- th:attrprepend = <input type="text" class="text" th:attrprepend="class='large'"/><br/>  
- th:classappend = <input type="text" class="text" th:classappend="large"/><br/>  
<h1>checked 처리</h1>  
- checked o <input type="checkbox" name="active" th:checked="true"/><br/>  
- checked x <input type="checkbox" name="active" th:checked="false"/><br/>  
- checked=false <input type="checkbox" name="active" checked="false"/><br/>  
</body>  
</html>
  • th:attrappend: 기존의 속성 뒤에 값을 추가(자주 사용 X)
  • th:attrprepend: 기존의 속성 앞에 값을 추가(자주 사용 X)
  • th:classappend: 기존의 클래스 뒤에 값 추가(가끔 사용할 일이 있다)

checked

HTML에서 input 속성에 checked=false로 되어있어도 checkBoxcheck가 되어있다.

<!DOCTYPE html>  
<html xmlns:th="http://www.thymeleaf.org">  
<head>  
...
<body>  
...
<h1>checked 처리</h1>  
- checked o = <input type="checkbox" class="active" th:checked="ture"/></br>  
- checked x = <input type="checkbox" class="active" th:checked="false"/></br>  
- checked=false = <input type="checkbox" class="active" checked="false"/>  
</body>  
</html>

th:checked=true

th:checked = true인 경우에만 checked=checked 속성이 생성 된다.
checked x = 의 경우를 보면 checked 속성 자체가 없는 것을 확인할 수 있다.

반복

반복문 자세히 알아보기
th:each를 사용, 컬렉션을 반복해서 렌더링 할 때 사용

 

templates/basic/each.html

...
<h1>기본 테이블</h1>  
<table border="1">  
    <tr>  
        <th>username</th>  
        <th>age</th>  
    </tr>  
    <tr th:each="user : ${users}">  
        <td th:text="${user.username}">username</td>  
        <td th:text="${user.age}">0</td>  
    </tr>  
</table>
...

기본적으로 th:each="요소: ${컬렉션}"처럼 사용한다. 자바의 for each와 거의 동일하다.

특이한 점은 현재 loop를 돌고 있는 컬렉션의 상태를 보여줄 수 있다.
th:each="요소, status : ${컬렉션}, status는 생략이 가능(생략하면 요소 + Stat로 생성)

status의 요소

  • index: 0부터 시작하는 값
  • count: 1부터 시작하는 값
  • size: 컬렉션 안에 있는 총요소의 값
  • current: 컬렉션에서 현재 몇 번째 요소인지 확인
  • even/odd: 현재 반복이 짝수인지 홀수인지 여부(index를 기준으로 판별이 아님)
  • first: 현재 반복이 첫 번째 반복인지 확인
  • last: 현재 반복이 마지막 반복인지 확인
<h1>반복 상태 유지</h1>  
<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}"></td>  
        <td th:text="${user.username}"></td>  
        <td th:text="${user.age}"></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(if의 반대)
조건부 평가 자세히 알아보기

<!DOCTYPE html>  
<html xmlns:th="http://www.thymeleaf.org">  
...
<body>  
<h1>if, unless</h1>  
<table border="1">  
    <tr>  
        <th>count</th>  
        <th>username</th>  
        <th>age</th>  
    </tr>  
    <tr th:each="user : ${users}">  
        <td th:text="${userStat.count}">1</td>  
        <td th:text="${user.username}">username</td>  
        <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>  
    </tr>  
</table>  
...
</body>  
</html>

if문에서는 나이가 20보다 작으면 미성년자라는 문자가 나옵니다.

unless에서는 나이가 20보다 크거나 같지 않으면(20보다 작으면) not if 느낌이기 때문에 if처럼 미성년자라는 문자가 나옵니다

Switch 문

th:switch로 사용 가능

<!DOCTYPE html>  
<html xmlns:th="http://www.thymeleaf.org">  
...
<body>  
...
<h1>switch</h1>  
<table border="1">  
    <tr>  
        <th>count</th>  
        <th>username</th>  
        <th>age</th>  
    </tr>  
    <tr th:each="user, userState : ${users}">  
        <td th:text="${userState.count}">1</td>  
        <td th:text="${user.username}">username</td>  
        <td th:switch="${user.age}">  
            <span th:case="10">10살</span>  
            <span th:case="20">20살</span>  
            <span th:case="*">기타</span>  
        </td>  
    </tr>  
</table>  
</body>  
</html>

조건에 맞는 case를 찾아서 데이터를 출력한다.

728x90