728x90
반응형
타임리프는 기본적으로 HTML 태그 안에 th: 로 시작하는 속성을 지정하여 사용한다.
타임리프에서 반복은 th:if / th:unless (if 반대) 를 사용한다. (개인적으로 가장 많이 사용하는 타임리프 속성이다)
switch 문은 th:switch 로 사용 가능하다.
<span th:if=${age == 20}></span>
<span th:unless=${age == 20}></span>
<div th:switch="${age}">
<span th:case="10">10살</span>
</div>
🎈if, unless 사용 예시
<!-- age == 20 -->
<span th:if=${age == 20}>나이는 20살</span>
<span th:if=${age == 30}>나이는 30살</span>
<span th:if=${age < 30}>나이는 30살 보다 적음</span>
<span th:unless=${age == 20}>20살 아님</span>
<span th:unless=${age == 40}>40살 아님</span>
<!-- ↓↓↓↓↓↓ 실제 렌더링된 HTML -->
<span>나이는 20살</span>
<span>나이는 30살 보다 적음</span>
<span>40살 아님</span>
th:if / th:unless
- 타임 리프는 조건이 맞지 않으면 태그 자체를 렌더링 하지 않는다. (렌더링 시 없애버림)
- ${...} 내부에 boolean 값을 넣으면 된다.
비교와 동등 판별
- 비교 : >, <, >=, <= (gt, lt, ge, le) - 'gt (greater than)'와 같은 문자로도 비교 가능.
- 동등 연산 : ==, != (eq, ne)
🎈switch 사용 예시
<!-- ${question.questionType.name()} == "SHORT" -->
<span th:switch="${question.questionType.name()}">
<th:block th:case="SHORT">
<p>단답형</p>
<p>응답해주세요.</p>
</th:block>
<th:block th:case="MULTIPLE">
<p>객관식</p>
<p>응답해주세요.</p>
</th:block>
<th:block th:case="*">
<p>응답해주세요.</p>
</th:block>
</span>
<!-- ↓↓↓↓↓↓ 실제 렌더링된 HTML -->
<span>
<p>단답형</p>
<p>응답해주세요.</p>
</span>
- th:block 은 HTML 태그가 아닌 타임리프의 유일한 자체 태그이다.
- 타임 리프의 기능을 위해 사용하며 특정 태그들을 한 블록으로 묶어놓을 수 있다.
- 렌더링 시 th:block 은 사라진다.
- * 은 만족하는 조건이 없을 때 사용하는 디폴트이다.
🎈조건 연산 예시
${...} 표현식 내부에서 조건에 따라 다른 값을 할당할 수 있다.
- if-then : (if) ? (then)
- if-then-else : (if) ? (then) : (else)
<!-- ${row.even} == true / ${row.first} == true -->
<tr th:class="${row.even}? 'even' : 'odd'">
...
</tr>
<tr th:class="${row.even}? (${row.first}? 'first' : 'even') : 'odd'">
...
</tr>
<tr th:class="${row.even}? 'col'">
...
</tr>
<!-- ↓↓↓↓↓↓ 실제 렌더링된 HTML -->
<tr th:class="even">
...
</tr>
<tr th:class="first">
...
</tr>
<tr th:class="col">
...
</tr>
- 다음과 같이 (조건, then : else) 을 사용하여 조건에 따라 속성에 다른 값이 할당되게끔 할 수 있다.
- 2번째 예시처럼 then절 이나 else절에도 조건문 넣을 수 있다.
- Default : (value) ?: (defaultvalue)
<!-- user.age에 아무 값도 없음 (null) -->
<div th:object="${session.user}">
...
<p>Age: <span th:text="*{age}?: '(no age specified)'">27</span>.</p>
<p>Age: <span th:text="*{age != null}? *{age} : '(no age specified)'">27</span>.</p>
</div>
<!-- ↓↓↓↓↓↓ 실제 렌더링된 HTML -->
<div">
...
<p>Age: <span>(no age specified)</span>.</p>
<p>Age: <span>(no age specified)</span>.</p>
</div>
- (value) ?: (defaultvalue) 문법을 사용하여 접근하려는 값이 null 일때 기본 값을 지정해줄 수 있다.
- 두번째 <p> 태그처럼 if-then-else : (if) ? (then) : (else) 문법을 사용해도 똑같이 동작한다.
참고
728x90
반응형