[Spring_Boot] Thymeleaf, 기본문법

최현석·2022년 11월 23일
0

Spring_Boot

목록 보기
7/31
post-thumbnail

🧩 thymeleaf

  • 타임리프는 순수 HTML을 최대한 유지하기 때문에 웹 브라우저에서
    파일을 직접 열어도 HTML 내용을 확인할 수 있음
    (퍼블리셔로부터 파일을 전달받을 때 리뷰하기 유용함)
  • 서버를 통해 뷰 템플릿을 거치면 동적으로 변경된 결과 확인 가능
  • 순수 HTML을 그대로 유지하면서 view template도 사용할 수 있는
    타임리프의 특징을 Natural Template 이라고 함.

1) 간단한 표현

  • 변수 표현식 : ${. .}
  • 선택 변수 표현식 : *{. .}
  • 메시지 표현식 : #{. .}
  • 링크 URL 표현식 : @{. .}
  • 조각 표현식 : ~{. .}

2) 리터럴

  • 텍스트 : 'text'
  • 숫자 : 0, 20, 3.14
  • 불린 : true, false
  • 널 : null

3) 기본 객체들

  • ${#request}
  • ${#response}
  • ${#session}
  • ${#servletContext}
  • ${#locale}

🧩 텍스트 , 표준 표현식 구문 실습

index

<body>
	<ul>
			<li> 텍스트
			<ul>
				<li><a href="/basic/text-basic">텍스트 출력 기본</a></li>
				<li><a href="/basic/text-unescaped">텍스트 text, utext</a></li>
			</ul>
		</li>
		
		<li>표준 표현식 구문
			<ul>
				<li><a href="/basic/variable">변수</a></li>
				<li><a href="/basic/basic-objects?paramData=paramValue">기본객체들</a></li>
				<li><a href="/basic/date">유틸리티 객체와 날짜</a></li>
				<li><a href="/basic/link">링크 URL</a></li>
				<li><a href="/basic/literal">리터럴</a></li>
				<li><a href="/basic/operation">연산</a></li>
			</ul>
		</li>
		
		<li>속성 값 설정
			<ul>
				<li><a href="/basic/attribute">속성 값 설정</a> </li>
			</ul>
		</li>
		
		<li>반복
			<ul>
				<li><a href="/basic/each">반복</a> </li>
			</ul>
		</li>
		
		<li>조건부 평가
			<ul>
				<li><a href="/basic/condition">조건부 평가</a> </li>
			</ul>
		</li>

		<li>주석
			<ul>
				<li><a href="/basic/comments">주석</a> </li>
				<li><a href="/basic/block">블럭</a> </li>
			</ul>
		</li>

		<li>자바스크립트 인라인
			<ul>
				<li><a href="/basic/javascript">자바스크립트 인라인</a> </li>
			</ul>
		</li>
		
		<li>템플릿 레이아웃
			<ul>
				<li><a href="/template/fragment">템플릿 조각</a> </li>
				<li><a href="/template/layout">유연한 layout</a> </li>
			</ul>
		</li>
	</ul>
</body>

BasicController

@Controller
// index에서 중복되는 url부분을 꺼내온다 
@RequestMapping("/basic")
public class BasicController {

	@GetMapping("text-basic")
	public String textBasic(Model model) {
		model.addAttribute("data","Hello!!");
		return "basic/text-basic";
	}
	
	@GetMapping("text-unescaped")
	public String textUnescaped(Model model) {
		model.addAttribute("data","<b>Hello!!<b>");
		return "basic/text-unescaped";
	}
	
	
	@GetMapping("variable")
	public String variable(Model model) {
		User userA = new User("UserA", 10);
		User userB = new User("UserB", 10);
		
		List<User> list = new ArrayList<User>();
		list.add(userA);
		list.add(userB);
		
		Map<String, User> map = new HashMap<String, User>();
		map.put("UserA", userA);
		map.put("UserB", userB);
		
		model.addAttribute("user",userA);
		model.addAttribute("users",list);
		model.addAttribute("userMap",map);
		
		return "basic/variable";
	}
	
	@GetMapping("basic-objects")
	public String basicObjects(HttpSession session) {
		session.setAttribute("sessionData", "sessionValue");
		return "basic/basic-objects" ;
	}
	
	@GetMapping("date")
	public String date(Model model) {
		model.addAttribute("localDateTime",LocalDateTime.now());
		return "basic/date" ;
	}
	
	
	@GetMapping("link")
	public String link(Model model) {
		model.addAttribute("param1","data1");
		model.addAttribute("param2","data2");
		return "basic/link" ;
	}
	
	@GetMapping("literal")
	public String literal(Model model) {
		model.addAttribute("data","spring");
		return "basic/literal" ;
	}
	
	@GetMapping("operation")
	public String operation(Model model) {
		model.addAttribute("data","spring");
		model.addAttribute("nullData",null);
		return "basic/operation" ;
	}
	
	@GetMapping("attribute")
	public String attribute(Model model) {
		return "basic/attribute" ;
	}
	
	@GetMapping("each")
	public String each(Model model) {
		addUser(model);
		return "basic/each" ;
	}

	@GetMapping("condition")
	public String condition(Model model) {
		addUser(model);
		return "basic/condition" ;
	}
	
	@GetMapping("comments")
	public String comments(Model model) {
		model.addAttribute("data","spring");
		return "basic/comments" ;
	}
	
	@GetMapping("block")
	public String block(Model model) {
		addUser(model);
		return "basic/block" ;
	}
	
	@GetMapping("javascript")
	public String javascript(Model model) {
		model.addAttribute("user",new User("userD",10));
		addUser(model);
		return "basic/javascript" ;
	}
	
	private void addUser(Model model) {
		List<User> list = new ArrayList<User>();
		list.add(new User("userA", 10));
		list.add(new User("userB", 20));
		list.add(new User("userC", 30));
		model.addAttribute("users",list);
	}
}

🧩 텍스트 출력 기본

text-basic.html

  • 타임리프는 html 태그안에 작성
  • 컨텐츠 안에서 직접 출력도 가능
<body>
	<h1>컨텐츠 데이터 출력하기</h1>
	<ul>
		<li>th:text 사용 = <span th:text="${data}"></span></li>
		<li>컨텐츠 안에서 직접 출력하기 = [[${data}]]</li>
	</ul>
</body>


🧩 텍스트 text, utext

text-unescaped.html

  • text, [[...]] : 있는 그대로 출력
  • utext, [(...)] : 의도한 대로 출력
  • th:inline="none" : 타임리프 언어로 해석하지 않고 출력
    사용하지 않을 시 ... 으로만 출력
<body>
	<h1>text vs utext</h1>
	<ul>
		<li>th:text = <span th:text="${data}"></span></li>	
		<li>th:utext = <span th:utext="${data}"></span></li>	
	</ul>
	
	<h1>
		<span th:inline="none">[[...]] vs [(...)]</span>
	</h1>
	<ul>
		<li><span th:inline="none">[[...]] = </span>[[${data}]]</li>
		<li><span th:inline="none">[(...)] = </span>[(${data})]</li>
	</ul>
</body>


🧩 변수

User

@Getter @Setter
public class User {

	private String username;
	private int age;
	
	public User(String username, int age) {
		super();
		this.username = username;
		this.age = age;
	}
}

variable.html

<body>
	<h1>표현식</h1>
	<ul>
		Object
		<li>
			${user.username} = <span th:text="${user.username}"></span>
		</li>
		<li>
			${user['username']} = <span th:text="${user['username']}"></span>
		</li>
		<li>
			${user.getUsername()} = <span th:text="${user.getUsername()}"></span>
		</li>
	</ul>
	
	<ul>
		List
		<li>
			${users[0].username} = <span th:text="${users[0].username}"></span>
		</li>
		<li>
			${users[0]['username']} = <span th:text="${users[0]['username']}"></span>
		</li>
		<li>
			${users[0].getUsername()} = <span th:text="${users[0].getUsername()}"></span>
		</li>
	</ul>
	
	<ul>
		Map
		<li>
			${userMap['UserA'].username}
				= <span th:text="${userMap['UserA'].username}"></span>		
		</li>
		<li>
			${userMap['UserA']['username']}
				= <span th:text="${userMap['UserA']['username']}"></span>		
		</li>
		<li>
			${userMap['UserA'].getUsername()}
				= <span th:text="${userMap['UserA'].getUsername()}"></span>		
		</li>
	</ul>
	
	<hr>
	<h1>지역변수 - (th:with)</h1>
  <--	first라는 변수에 첫번째 객체를 할당 -->
	<div th:with="first=${users[0]}">
		<p>
			처음 사람의 이름은 <span th:text="${first.username}"></span>		
		</p>
	</div>
</body>


🧩 기본객체들

HelloBean

// helloBean 스프링 컨테이너 영역에 등록하고 싶을 때
// 싱글톤으로 어디서든 쉽게 꺼내쓸수있게 영역에 넣고싶을 때
@Component("helloBean")
public class HelloBean {

	public String hello(String data) {
		return "Hello " + data;
	}
}

basic-objects.html

<body>
	<h1>기본 객체</h1>
	<ul>
		<li>request = <span th:text="${#request}"></span></li>
		<li>response = <span th:text="${#response}"></span></li>
		<li>session = <span th:text="${#session}"></span></li>
		<li>servletContext = <span th:text="${#servletContext}"></span></li>
		<li>locale = <span th:text="${#locale}"></span></li>
	</ul>
	
	<hr>
	
	<h1>편의 객체</h1>
	<ul>
		<li>Request Parameter = 
			<span th:text="${#httpServletRequest.getParameter('paramData')}"></span>
		</li>
		<li>Request Parameter2 = 
			<span th:text="${#request.getParameter('paramData')}"></span>
		</li>
		<li>Request Parameter3 = 
			<span th:text="${param.paramData}"></span>
		</li>
		<li>session = 
			<span th:text="${session.sessionData}"></span>
		</li>
		<li>
			spring bean = 
				<span th:text="${@helloBean.hello('user!')}"></span>
		</li>
	</ul>
	
</body>


🧩 유틸리티 객체와 날짜

text-date.html

<body>
	<h1>LocalDateTime</h1>
	<ul>
		<li> default = <span th:text="${localDateTime}"></span> </li>
		<li> yyyy-MM-dd HH:mm:ss =
			<span th:text="${#temporals.format(localDateTime,'yyyy-MM-dd HH:mm:ss')}"></span> 
		</li>
	</ul>
	
	<hr>
	<h1>LocalDateTime</h1>
	<ul>
		<li>${#temporals.day(localDateTime)}=
			<span th:text="${#temporals.day(localDateTime)}"></span>
		</li>
		<li>${#temporals.month(localDateTime)}=
			<span th:text="${#temporals.month(localDateTime)}"></span>
		</li>
		<li>${#temporals.monthName(localDateTime)}=
			<span th:text="${#temporals.monthName(localDateTime)}"></span>
		</li>
		<li>${#temporals.year(localDateTime)}=
			<span th:text="${#temporals.year(localDateTime)}"></span>
		</li>
		<li>${#temporals.dayOfWeek(localDateTime)}=
			<span th:text="${#temporals.dayOfWeek(localDateTime)}"></span>
		</li>
		<li>${#temporals.dayOfWeekName(localDateTime)}=
			<span th:text="${#temporals.dayOfWeekName(localDateTime)}"></span>
		</li>
		<li>${#temporals.hour(localDateTime)}=
			<span th:text="${#temporals.hour(localDateTime)}"></span>
		</li>
		<li>${#temporals.minute(localDateTime)}=
			<span th:text="${#temporals.minute(localDateTime)}"></span>
		</li>
		<li>${#temporals.second(localDateTime)}=
			<span th:text="${#temporals.second(localDateTime)}"></span>
		</li>
	</ul>
		
</body>


🧩 링크 URL

link.html

<body>
	<h1>url 링크</h1>
	<ul>
		<li>
			<a th:href="@{/hello}">basic url</a>
		</li>
		<li>
			<a th:href="@{/hello(param1=${param1}, param2=${param2})}">param url</a>
		</li>
		<li>
			<a th:href="@{/hello/{param1}/{param2}(param1=${param1},param2=${param2})}">
			path url</a>
		</li>
		<li>
			<a th:href="@{/hello/{param1}(param1=${param1},param2=${param2})}">
			param + path url</a>
		</li>
	</ul>
	
</body>

🧩 리터럴(Literals)

  • 리터럴은 소스 코드상에 고정된 값을 말하는 용어이다.
  • "Hello" 문자 리터럴, 10, 20 은 숫자 리터럴이다.
  • 문자 : 'hello'
    숫자 : 10
    불린 : true, false
    null : null
  • 타임리프에서 문자 리터럴은 항상 ' '(작은 따옴표)로 감싸야 한다.
<span th: text="'hello'">
  • 공백없이 쭉 이어지는 하나의 리터럴은 작은 따옴표를 생략할 수 있다.
   		<span th: text="hello">
		<span th: text="hello world!">		(오류)
		<span th: text="'hello world!'">	(정상)

literal

	<h1>리터럴</h1>
	<ul>
<!-- ''없는 오류	<li>"hello world!" = <span th:text="hello world!"></span> </li> -->
		<li>'hello' + 'world!' = <span th:text="'hello' + 'world!'"></span> </li>
		<li>'hello world!' = <span th:text="'hello world!'"></span> </li>
		<li>'hello ' + ${data} = <span th:text="'hello 	' + ${data}"></span> </li>
		<li>리터럴 대체 |hello ${data}| = <span th:text="|hello ${data}|"></span> </li>
		
	</ul>

🧩 연산

  • 비교연산 : HTML 태그 주의
  • , >(gt/%gt;), <(lt), >=(ge), <=(le), !(not), ==(eq), !=(neq, ne)
  • 조건식
  • ELvis 연산자

operation

<body>
	<ul>
		<li>산술연산
			<ul>
				<li>10 + 2 = <span th:text="10 + 2"></span></li>
				<li>10 % 2 == 0 = <span th:text="10 % 2 == 0"></span></li>
			</ul>
		</li>
		<li>비교연산
			<ul>
				<li>1 > 10 = <span th:text="1 &gt; 10"></span></li>
				<li>1 gt 10 = <span th:text="1 gt 10"></span></li>
				<li>1 >= 10 = <span th:text="1 >= 10"></span></li>
				<li>1 ge 10 = <span th:text="1 ge 10"></span></li>
				<li>1 == 10 = <span th:text="1 == 10"></span></li>
				<li>1 != 10 = <span th:text="1 != 10"></span></li>
			</ul>
		</li>
		<li>조건식
			<ul>
				<li>(10 % 2 == 0) ? '짝수':'홀수' == 
					<span th:text="(10 % 2 == 0) ? '짝수':'홀수'"></span>
				</li>
			</ul>
		</li>
		<li>Elvis 연산자
			<ul>
				<li>${data}?: '데이터가 없습니다.' =  
					<span th:text="${data}?: '데이터가 없습니다.'"></span>
				</li>
				<li>${nullData}?: '데이터가 없습니다.' =  
					<span th:text="${nullData}?: '데이터가 없습니다.'"></span>
				</li>
			</ul>
		</li>
		<li>no-operation
			<ul>
				<li>${data}?: _ =  
					<span th:text="${data}?: _">데이터가 없습니다.</span>
				</li>
				<li>${nullData}?: '데이터가 없습니다.' =  
					<span th:text="${nullData}?: '데이터가 없습니다.'"></span>
				</li>
			</ul>
		</li>
	</ul>

</body>

🧩 속성 값 설정

  • ht :* 로 속성을 적용하면 기존 속성을 대체한다.
  • 기존 속성이 없으면 새로 만든다.

attribute

<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 = false
		<input type="checkbox" name="active" checked="false">
	<br>
	- checked x
		<input type="checkbox" name="active" th:checked="false">
	<br>
	- checked o
		<input type="checkbox" name="active" th:checked="true">
</body>

🧩 반복 상태 유지

  • 반복의 두번째 파라미터를 설정해서 반복의 상태를 확인 할 수 있다.
  • 두번째 파라미터는 생략 가능한데, 생략하면 지정한 변수명 (user) + Stat
    여기서는 user + Stat = userStat
  • userStat
    -> index : 0 부터 시작하는 값
    -> count : 1부터 시작하는 값
    -> size : 전체 사이즈
    -> even, odd : 홀, 짝 여부(boolean)
    -> first, last : 처음, 마지막 여부(boolean)
    -> current : 현재 객체 주소값

each

<body>
	<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>
	<hr>

	<h1>반복 상태 유지</h1>
	<table border="1">
		<tr>
			<th>count</th>
			<th>username</th>
			<th>age</th>
			<th>etc</th>
		</tr>
<!-- 		userStat :thymeleaf 지원 -->
		<tr th:each=" user, userStat : ${users} ">
			<td th:text="${userStat.count}"></td>
			<td th:text="${user.username}">username</td>
			<td th:text="${user.age}">0</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>
</body>

🧩 조건부 평가

  • if, unless(if의 반대)
  • 타임리프는 해당 조건이 맞지 않으면 태그 자체를 렌더링하지 않는다.

condition

<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}"></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}">0</span>
				<span th:text="'미성년자'" th:unless="${user.age ge 20}">0</span>
			</td>
		</tr>
	</table>
	
	<hr>
	
	
	<table border="1">
		<tr>
			<th>count</th>
			<th>username</th>
			<th>age</th>
		</tr>
		<tr th:each=" user : ${users} ">
			<td th:text="${userStat.count}"></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>

🧩 블록

<th:block>은 HTML태그가 아닌 타임리프의 유일한 자체 태그다.

block

<body>
	
	<th:block th:each="user : ${users}">
		<div>
			사용자 이름1 <span th:text="${user.username}"></span>
			사용자 나이1 <span th:text="${user.age}"></span>
		</div>
		<div>
			요약 <span th:text="${user.username} + '/' + ${user.age}"></span>
		</div>
		
	</th:block>
</body>
   

🧩 주석

comments

<body>
	<h1>예시</h1>
	<span th:text="${data}">html data</span>
	
	<h1>1. 표준 HTML 주석</h1>
<!-- 	<span th:text="${data}">html data</span> -->
	<h1>2. 타임리프 주석</h1>
	<!--/* [[${data}]] */-->
	<br>
	
	<!--/* -->
	<span th:text="${data}">html data</span>
	<!-- */-->
</body>

🧩 자바스크립트 인라인

  • 타임리프는 자바스크립트에서 타임리프를 편하게 사용할 수 있는
    자바스크립트 인라인 기능을 제공한다.
<script th:inlin="javascript">

javascript

<body>
	<!-- 자바스크립트 인라인 사용 전  -->
	<script>
		let username = "[[${user.username}]]";
		let age = [[${user.age}]];
		
		// 객체
// 		let user = [[${user}]];
	</script>
	
	<!-- 자바스크립트 인라인 사용 후  -->
	<script th:inline="javascript">
		let username20 = [[${user.username}]];
		let age20 = [[${user.age}]];
		
		// 객체
		let user20 = [[${user}]];
	</script>
	
	<!-- 자바스크립트 인라인 each -->
	<script th:inline="javascript">
		[# th:each="user, stat : ${users}"]
			let user[[${stat.count}]] = [[${user}]];
		[/]
	</script>
	
</body>

🧩 템플릿 레이아웃

TemplateController

@Controller
@RequestMapping("template")
public class TemplateController {

	@GetMapping("fragment")
	public String fragment() {
		return "template/fragment/fragmentMain";
	}
	
	@GetMapping("layout")
	public String layout() {
		return "template/layout/layoutMain";
	}
	
}

fragmentMain

<body>
	<h1>부분포함</h1>
	
	<h2>부분포함 insert</h2>
	<div th:insert="~{template/fragment/footer :: copy}"></div>

	<h2>부분포함 replace</h2>
	<div th:replace="~{template/fragment/footer :: copy}"></div>

	<h2>부분포함 단순 표현식</h2>
	<div th:replace="template/fragment/footer :: copy"></div>

	<h1>파라미터 사용</h1>
	<div th:replace="~{template/fragment/footer :: copyParam('data1','data2')}"></div>
	
</body>
<body>
	<footer th:fragment="copy">
		footer 자리입니다.
	</footer>

	<footer th:fragment="copyParam(param1, param2)">
		<p>파라미터 자리입니다.</p>
		<p th:text="${param1}"></p>
		<p th:text="${param2}"></p>
	</footer>
	
</body>

layoutMain

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="template/layout/base :: common_header(~{::title}, ~{::link})">
<meta charset="UTF-8">
<title>메인 타이틀</title>

<link rel="stylesheet" th:href="@{/css/chart.min.css}">
<link rel="stylesheet" th:href="@{/themes/jquery.min.css}">
</head>
<body>
	메인 컨텐츠
</body>
</html>

base

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<!-- 전체 사이트에서 가져다 쓰는 공통 layout -->

<head th:fragment="common_header(title,links)">

<meta charset="UTF-8">
<title th:replace="${title}">레이아웃 타이틀</title>

<!-- 공통 -->
	<link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.css}">
	<script type="text/javascript" th:src="@{/sh/scripts/base.js}"></script>
	
<!-- 추가 -->
	<th:block th:replace="${links}"/>
	
	
		
</head>
<body>

</body>
</html>

0개의 댓글