Flaming Soccer ball
SPRING BOOT

97일차 Spring Boot Thymeleaf

leo lee 2023. 2. 13.
반응형

타임리프

타임리프thymeleaf 는 자바 라이브러리이며, 텍스트, HTML, XML, Javascript, CSS 그리고 텍스트를 생성할 수 있는 템플릿 엔진

스프링 MVC와의 통합 모듈을 제공하며, 애플리케이션에서 JSP로 만든 기능들을 완전히 대체

Spring Boot에서는 JSP가 아닌 Thymeleaf 사용을 권장

 

 

타임리프 문법

*공식홈페이지 http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

타임리프는 최상단에 xmlns:사용명을 반드시 명시

설명 표현식
변수 표현  ${...} ${session.user}
선택자  *{...}  *{firstName}
메시지  #{...} #{message}
링크  @{...}  @{abbo.tistory.com}
fragment expression  ~{...}  frag=~{footer::#main/text()}
텍스트  '...'  'text1'
숫자    0, 1, 3.14
불리언    true, false
Null    null
리터럴 문자    one, main
텍스트 결합  ${str1}+${str2}
문장 결합  |  |My name is ${name}|
숫자 연산  +, -, *, /, %  1+2-3*4/5%2
음수 기호  -  
조건 연산  and, or, !, not  ${condition1} and ${condition2}
비교 연산  >, <, >=, <=, gt, lt, ge, le  ${number1} > 3

빨간 부분을 중점적으로 보면 된다.

 

HTML Tag 내에 property명 앞에 'th:'를 붙입니다.

설명 표현식 예시
th:text  텍스트 내용 출력 <span th:text="${name}"></span>
th:value  Value 수정(input, checkbox 등) <input type="text" th:value="${val}" />
th:with  변수값 지정 <div th:with="var1=${user.name}"></div>
th:if
th:unless
조건문(if, else) <p th:if="${user.authType}=='web'" th:text="${user.authType}"></p>
th:each  반복문  <p th:each="user : ${users}" th:text="${user.name}"></p>
th:href  a태그 <a th:href=“@{경로}” >내용</a>
th:block  별도의 태그 없이 제어문 사용 <th:block th:each="vo : ${list}"></th:block>
th:inline="javascript"  자바스크립트에서 타임리프 사용 <script th:inline="javascript"></script>

 

th:text/ th:value/ th:with

예시

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"><!-- 타임리프 명시적 선언 -->
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>타임리프 출력과 변수</h3>
	
	<!-- 타임리프 문법을 사용하려면 속성 앞에 th를 붙입니다  -->
	<h3 th:text="${'헬로월드'}"></h3>
	<h3>[[${'헬로월드'}]]</h3>
	
	<h3 th:text="${1==1}"></h3>
	<h3>[[${1==1}]]</h3>

	<h3 th:text="${true and false}"></h3>
	<h3>[[${true and false}]]</h3>
	
	<h3>[[${'가' eq '가나다'}]]</h3>
	
	<hr/>
	
	<!-- 변수 선언 -->
	<div th:with="a=10">
		a: [[${a}]]
	</div>
	
	<div th:with="a= '홍길동'" th:text="${a}">
	
	</div>
	
	<!-- value 속성의 사용  -->
	<div th:with="a= '이순신'" >
		<input type="text" th:value="${a}">
	</div>
	
	<hr/>

	
</body>
</html>

 

결과

 

th:if/ th:unless

예시

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"><!-- 타임리프 명시적 선언 -->
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>타임리프 출력과 변수</h3>
	
	<!-- if문 -->
	<div th:with="a= 10">
		<span th:if="${a==10}">[[${a + '입니다'}]]</span>
		<span th:if="${a==20}">[[${a + '입니다'}]]</span>
	</div>
	
	<!-- if else문: unless는 동일한 조건을 적습니다 -->
	<div th:with="a= 10">
		<span th:if="${a}!=10">[[${a + '입니다'}]]</span>
		<span th:unless="${a}!=10">[[${a + '입니다'}]]</span>
	</div>
	
	<!-- 삼항연산자 -->
	<div th:with="a= 10">
		[[${a == 10 ? '참' : '거짓'}]]<br/>
		[[${a} == 10 ? '참' : '거짓']]<br/>
	</div>
	
</body>
</html>

결과

 

 

th:each

예시

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"><!-- 타임리프 명시적 선언 -->
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>반복문</h3>
	[[${list}]]
	<ul>
		<li th:each="vo : ${list}">
			[[${vo.name}]]
			[[${vo.age}]]
		</li>
	</ul>
	<hr/>
	<h3>반복문과 state변수(jstl = varState)</h3>
	<!-- each에 두번째 변수를 선언하면 상태값을 담아줌 (index, count, size, current 등-->
	<ul>
		<li th:each="vo, a: ${list}">
		
			[[${a.count}]]번 - [[${vo.name}]]
		</li>
	</ul>
	<hr/>
	
	<h3>반복문과 조건문</h3>
	<ul>
		<li th:each="vo: ${list}" th:if="${vo.age % 2 == 0}">
			[[${vo.age + '는 짝수'}]]
		</li>
	</ul>
	<hr/>
	
	<h3>반복문과 조건문2</h3>
	<ul>
		<li th:each="vo: ${list}" >
			<span th:if="${vo.age % 2 == 0}">짝수</span>
			<span th:unless="${vo.age % 2 == 0}">홀수</span>
		</li>
	</ul>
	<hr/>
	
	
</body>
</html>

 결과

 

 

th:block/ th:href

예시

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"><!-- 타임리프 명시적 선언 -->
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>타임리프 block문</h3>
	[[${list}]]
	<hr/>
	
	<!-- block 은 별도의 태그를 사용하지 않고, 마치 중괄호 처럼 사용하고 싶을 때 적용  -->
	<ul>
		<th:block th:each="vo: ${list}">
		<li>[[${vo}]]</li>
		</th:block>
	</ul>
	
	<hr/>
	<h3>타임리프 a태그</h3>
	<a href="test?a=10">일반 a태그</a>
	<a th:href=@{test?a=10}>타임리프 a태그</a>
	
	
	<!--  
		a링크로 값을 넘기는 방법
		경로(키=값)
		
		경로/변수/변수 (변수=값, 변수=값)
	-->
	<ul>
		<li th:each="vo: ${list}">
			<a th:href="@{test(age=${vo.age},name=${vo.name})}">키값 넘기기</a>
			
			<a th:href="@{test2/{age}/{name}(age=${vo.age},name=${vo.name})}">키값 넘기기(쿼리파라미터)</a>
		</li>
	</ul>
</body>
</html>

 

 

결과

첫번재 a링크 클릭 시 주소

두번째 a링크 클릭 시 주소

 

 

 

th:inline

 

예시

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"><!-- 타임리프 명시적 선언 -->
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	[[${name}]]
	[[${vo}]]
	
	<!-- 컨트롤러에서 보내는 값을 JSON문자열 형태로 받아줌 -->
	<script th:inline="javascript">
	
		var aa ='[[${name}]]'
		var bb ='[[${vo}]]'
		
		console.log(JSON.parse(aa));
		console.log(JSON.parse(bb));
	
	</script>
</body>
</html>

 

결과

 

 

타임리프 내장함수

 

타임리프는 Utility Object함수들을 내장으로 가지고 있음

자바의 String 내부에 기본적으로 내장되어 있는 여러 함수

 

${#내장함수} 내용이 많아서 잘 정리된 블로그를 첨부

(필요하다면 찾아서 사용)

https://abbo.tistory.com/56

 

Thymeleaf Utility Objects (1)

Author: 니용 이전 글에서 Thymeleaf의 기본적인 문법을 확인하였다면, 이번 글에서는 Thymeleaf를 더 심도 있게 활용할 수 있는 방법을 알려드리려고 합니다. Thymeleaf는 Utility Object라고 하는 함수를 기

abbo.tistory.com

 

예시

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"><!-- 타임리프 명시적 선언 -->
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>타임리프 내장함수</h3>
	[[${regdate}]]
	<br/>
	[[${#temporals.format(regdate, 'yyyy-MM-dd')}]]
	<br/>
	[[${#strings.substring('홍길동', 0, 1)}]]
</body>
</html>

 

결과

 

 

타임리프 include

 

예시

ex06 파일

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"><!-- 타임리프 명시적 선언 -->

<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>타임리프 include</h3>
	<!-- fragment를 가져오기 ~{경로:: 가져올 이름}-->
	<div th:replace="~{/include/layout01 :: part1}"></div>
	<th:block th:replace="~{/include/layout01 :: part2}"></th:block>
	
	<!-- 파일을 통째로 가져오려면 ~{경로} -->
	<th:block th:replace="~{/include/layout02}"></th:block>
</body>
</html>

layout01 파일

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"><!-- 타임리프 명시적 선언 -->
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div th:fragment="part1">
		<h3>프래그먼트1</h3>
	</div>
	
	<div th:fragment="part2">
		<h3>프래그먼트2</h3>
	</div>
</body>
</html>

layout02 파일

<header>
	<nav>
		<ul>
			<li><a href=#>메뉴</a></li>
			<li><a href=#>메뉴</a></li>
			<li><a href=#>메뉴</a></li>
			<li><a href=#>메뉴</a></li>
		</ul>
	</nav>
</header>

 

 

결과

 

 

예시

ex07 파일

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<!-- 타임리프 명시적 선언 -->
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<!-- ~{파일경로 :: 템플릿함수()} -->
	<th:block th:replace="~{/include/layout03 :: 함수( ~{ :: .second} ) }" >
		<div id="first">
			아이디 선택자 #
		</div>

		<div class="second">
			클래스 선택자 .
		</div>
		
	</th:block>
	<script>
		console.log("이 파일 에서만 사용");
	</script>

</body>
</html>

layout03파일

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<th:block th:fragment="함수(section)">
	<head>
<meta charset="UTF-8">
<title>Insert title here.</title>
	</head>
	<body>
		<header> 공통 템플릿 헤더 </header>

		<section th:replace="${section}"></section>

		<footer> 공통 템플릿 푸터 </footer>
	</body>
</th:block>
</html>

결과

 

 

실습

예시

quiz01 파일

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<th:block th:replace="~{/include/layout03 :: 함수( ~{ :: .wrap} ) }">

	<h3>이 화면에 진입할 때 SimpleVO를 이용하여 데이터를 출력 합니다. (값은 아무거나)</h3>
	<p>회원정보확인 링크에는 quiz_result01?키=값 형태로 회원번호, 이름, 아이디 을 넘겨주세요 아래
		class="wrap" 부분만 layout03 템플릿에 전달 될 수 있도록 처리하세요</p>

	<div class="wrap">
		회원번호:<br /> 이름:<br /> 아이디:<br /> <br> <a
			th:href="@{quiz_result01(iNum=${vo.iNum}, name=${vo.name}, id=${vo.id})}">회원정보확인</a>
	</div>

</th:block>
</html>

 

quiz_result01 파일

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>quiz01결과 확인</h3>
	회원번호: [[${iNum}]]<br/> 
	이름: [[${name}]]<br/> 
	아이디: [[${id}]]<br/>
</body>
</html>

결과

 

 

반응형

'SPRING BOOT' 카테고리의 다른 글

100일차 REST API  (0) 2023.02.22
99일차 Spring Boot 판매자 페이지 구현 실습  (1) 2023.02.22
98일차 Spring Boot DB 연결  (0) 2023.02.15
98일차 Spring Boot Validation  (0) 2023.02.15
96일차 Spring Boot  (0) 2023.02.13

댓글