본문 바로가기
Spring

[Spring] 타임리프 사용법

by 기록하는_사람 2022. 11. 16.

타임리프 사용법 - 직접 문자 삽입

📌 직접 문자 삽입

: th:text=""로 문자 출력 가능.

  출력 부분에 '${ }' 사용 가능.

<h1 th:text="hello">표시하는 부분</h1>

 

타임리프 사용법 - 인라인 처리

📌 인라인 처리

: [ [ $ { } ] ]

  태그를 속성에 추가하는 대신 본문에 변수를 포함할 수 있음. 

<h1>hi! [[${name}]]!!</h1>

 

타임리프 사용법 - 값 결합

📌 값 결합

: + 사용해 값 결합 가능.

<h1 th:text="'오늘은 ' + '일요일 ' + '입니다.'">표시하는 부분</h1>

 

📌 값 결합(리터럴 치환)

: | 문자 |

  문자 안에서 ${ } 사용 가능.

<h1 th:text="|hi ${name}!!|">표시하는 부분</h1>

 

타임리프 사용법 - 지역 변수

📌 지역 변수

: th:with="변수 이름 = 값"으로 변수에 값 할당 가능.

  정의된 태그 내부에서만 사용 가능.

  산술 연산자 사용 가능. 

<div th:with="a=1, b=2">
	<span th:text="|${a} + ${b} = ${a+b}|"></span>
</div>

 

타임리프 사용법 - 비교와 등가

📌 비교와 등가

: >, <, >=, <=, ==, != 사용 가능. 

<span th:text="1 > 10"></span>
<span th:text="1 < 10"></span>
<span th:text="1 >= 10"></span>
<span th:text="1 >= 10"></span>
<span th:text="1 == 10"></span>
<span th:text="1 != 10"></span>
<span th:text="lee == lee"></span>
<span th:text="lee != lee"></span>

 

타임리프 사용법 - 조건 연산자

📌 조건 연산자

: 삼항 연산자(<조건> ? <값1> : <값2>) 사용 가능.

  <조건>이 true면 값 1, false면 값 2가 출력됨.

<p th:text="${name} == 'lee' ? 'yes, lee' : 'not, lee'"></p>

 

타임리프 사용법 - 조건 분기

📌 조건 분기 - true

: th:if="조건"

  true인 경우, th:if에서 작성한 태그와 자식 요소 표시. 

<div th:if="${name} == 'lee'">
	<p> yes, lee</p>
</div>

 

📌 조건 분기 - false

: th:unless="조건

  false인 경우, th:unless에서 작성한 태그와 자식 요소 표시.

<div th:unless="${name} == 'lee'">
	<p> not, lee</p>
</div>

 

타임리프 사용법 - switch

📌 switch

: th:switch값과 th:case 값이 동일한 경우, HTML 요소 출력.

  일치하는 값이 없는 경우는 th:case="*"로 지정.

<div th:switch="${name}">
    <p th:case="lee" th:text="|${name}입니다.|"><p/>
    <p th:case="park" th:text="|${name}입니다.|"><p/>
    <p th:case="kim" th:text="|${name}입니다.|"><p/>
    <p th:case="*" th:text="X"><p/>
</div>

 

타임리프 사용법 - 참조

📌 참조 - 데이터를 결합한 객체

: 캡슐화된 필드를 참조하는 경우 public 접근 제한자의 getXxx( )라는 getter 메서드 작성해,

  '객체명.필드' 형식으로 값 참조 가능. 

  '객체명['필드']로 참조 가능.

<span th:text="${mb.id}">ID</span> - <span th:text="${mb.name}">이름</span><br>
<span th:text="${mb['id']}">ID</span> - <span th:text="${mb['name']}">이름</span><br>

 

📌 참조 - th:object

: 데이터를 저장한 객체를 th:object로 설정하고, 자식 요소에서 '*{필드명}'으로 사용.

<div th:object="${mb}">
    <span th:text="*{id}">ID</span> - <span th:text="*{name}">이름</span><br>
    <span th:text="*{['id']}">ID</span> - <span th:text="*{['name']}">이름</span><br>
</div>

 

📌 참조 - List

: 인덱스 번호로 참조 가능.

<span th:text="${list[0]}">list</span>
<span th:text="${list[1]}">list</span>
<span th:text="${list[2]}">list</span>
<span th:text="${list[3]}">list</span>

 

📌 참조 - Map

: 키 값, 'map.key'형식, map['키']으로 참조 가능. 

<span th:text="${map.park.name}">이름 1</span> - <span th:text="${map.kim.name}">이름 2</span>
<span th:text="${map['park']['name']}">이름 1</span> - <span th:text="${map['kim']['name']}">이름 2</span>

 

타임리프 사용법 - 반복

📌 반복

: th:each="<요소 저장용 변수> : ${ <반복 처리하는 객체> }"

  <요소 저장용 변수>는 반복 처리 중에만 유효함.

  Iterable 인터페이스를 구현한 클래스라면 th:each로 반복 처리 가능.

<div th:each="member : ${members}">
	<p>[[${member.id}]] : [[${member.name}]]</p>
</div>

 

타임리프 사용법 - 반복 상태

📌 반복 상태

: th:each="<요소 저장용 변수>, <상태 변수> : <반복 처리하는 객체>"

<div th:each="member, s : ${members}" th:object="${member}">
	<p>
    	index-> [[${s.index}]], count-> [[${s.count}]],
        size-> [[${s.size}]], current-> [[${s.current}]],
        even-> [[${s.even}]], odd-> [[${s.odd}]],
        first-> [[${s.first}]], last-> [[${s.last}]],
        [[*{id}]] : [[*{name}]]
	</p>
</div>

 

📌 반복 상태 변수

index 0부터 시작하는 인덱스로, 현재 인덱스 표시함.
count 1부터 시작하는 인덱스로, 현재 인덱스 표시함.
size 반복 처리하는 객체의 사이즈 표시함.
current 현재 반복 요소의 객체를 표시함.
even 현재 요소가 짝수 번째인지 여부 결정.
odd 현재 요소가 홀수 번째인지 여부 결정.
first 현재 요소가 첫 번째 요소인지 결정.
last 현재 요소가 마지막 요소인지 결정.

 

타임리프 사용법 - 유틸리티 객체

📌 유틸리티 객체

: 자주 사용하는 클래스를 상수로 정의한 것.

 

📌 유틸리티 객체 목록

#strings 문자 관련 편의 기능.
#numbers 숫자 서식 지원.
#bools Boolean 관련 기능.
#dates java.util.Date 서식 지원.
#objects 객체 관련 기능.
#arrays 배열 관련 기능.
#lists List 관련 기능.
#sets Set 관련 기능.
#maps Map 관련 기능.

 

📌 #numbers

#numbers.formatInteger( ) 정숫값 형식 변환.
#numbers.formatDecimal( ) 부동 소수점 형식 변환.
'COMMA' 쉼표 사용.
'POINT' 소수점 사용.

 

📌 #dates

#dates.createNow( ) 현재 날짜와 시간.
#dates.format( ) 날짜가 담긴 변수와 포맷 변환 문자열 지정.
#dates.year( ) 년.
#dates.month( ) 월.
#dates.day( ) 일.
#dates.dayOfWeek( ) 요일을 나타내는 정수.

 

📌 #strings

#strings.toUpperCase( ) 대문자로 변환.
#strings.isEmpty( ) 비어있는 지.
#strings.length( ) 문자열 길이.

 

타임리프 사용법 - 다른 템플릿 삽입하기 

📌 프래그먼트화

: 여러 템플릿에서 같은 내용이 사용되는 경우 공통 내용을 별개의 파일로 만들고 필요한 부분에 추가하는 것. 

 

📌 프래그먼트 사용법

① th:fragment 속성을 지정한 요소 내의 자식 요소가 프래그먼트 대상이 됨.

   속성에는 프래그먼트를 식별할 이름을 지정.

<span th:fragment="one">하나<span>
<span th:fragment="two">둘<span>
<span th:fragment="three">셋<span>

② th:insert로 프래그먼트 삽입.

    th:insert="fragment :: <프래그먼트 파일명>"

③ 전체 내용을 프래그먼트로 완전히 바꾸려면, th:replace 사용.

<div id="one" th:insert="fragment :: one"></div>
<div id="three" th:replace="fragment :: three"></div>

<div id="one">
	<span>하나</span>
</div>
<span>셋</span>

 

타임리프 사용법 - 레이아웃 

📌 레이아웃화

: 템플릿에서 같은 디자인 레이아웃을 사용하는 경우, 공통 레이아웃을 만들고 공유하는 것.

 사용하려면 전용 라이브러리인 thymeleaf-layout-dialect 필요.

 

📌 Thymeleaf Layout Dialect

- Decorator : 공통 레이아웃.

- Fragment : 공통 레이아웃을 사용하는 측.

 

📌 Thymeleaf Layout Dialect 단점

: 전체 화면을 타임리프의 변환 처리 후에 확인 가능함. 

 

댓글