텍스트 출력 - text, utext
<span th:text="${data}"> // HTML의 콘텐츠(content)에 데이터 출력
[[${data}]] // HTML 콘텐츠 영역 안에서 직접 데이터 출력
- 타임리프가 제공하는 th:text , [[...]] 는 기본적으로 이스케이스(escape)를 제공
- ex) < → < > → >
- Unescape (꼭 필요할 때만 사용)
- th:text → th:utext
- [[...]] → [(...)]
변수 - SpringEL
변수 표현식: ${...}
- Object
- user.username : user의 username을 프로퍼티 접근
- user['username'] : 위와 같음 user.getUsername()
- List
- users[0].username : List에서 첫 번째 회원을 찾고 username 프로퍼티 접근
- users[0]['username'] : 위와 같음
- Map
- userMap['userA'].username : Map에서 userA를 찾고, username 프로퍼티 접근
- userMap['userA']['username'] : 위와 같음
th:with 를 사용하면 지역 변수를 선언해서 사용 가능
<div th:with="first=${users[0]}">
<p><span th:text="${first.username}"></span></p>
유틸리티 객체
Tutorial: Using Thymeleaf
1 Introducing Thymeleaf 1.1 What is Thymeleaf? Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. The main goal of Thymeleaf is to provide a
www.thymeleaf.org
- ex)
<span th:text="${#temporals.format(localDateTime, 'yyyy-MM-dd HH:mm:ss')}"></span>
URL 링크
@{...} 문법 사용
<li><a th:href="@{/hello(param1=${param1}, param2=${param2})}">hello query param</a></li>
<li><a th:href="@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}">path variable</a></li>
<li><a th:href="@{/hello/{param1}(param1=${param1}, param2=${param2})}">path variable + query parameter</a></li>
단순한 URL
@{/hello} // /hello
쿼리 파라미터
- () 에 있는 부분은 쿼리 파라미터로 처리
// /hello?param1=data1¶m2=data2
@{/hello(param1=${param1}, param2=${param2})}
경로 변수
- URL 경로상에 변수가 있으면 () 부분은 경로 변수로 처리
// /hello/data1/data2
@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}
경로 변수 + 쿼리 파라미터
// /hello/data1?param2=data2
@{/hello/{param1}(param1=${param1}, param2=${param2})}
리터럴
- 타임리프에서 문자 리터럴은 항상 ' (작은 따옴표)로 감싸야 함
- 리터럴 대체(Literal substitutions)
- <span th:text="|hello ${data}|">
- 리터럴 대체 문법을 사용하면 마치 템플릿을 사용하는 것 처럼 편리
연산
- 비교연산: HTML 엔티티를 사용해야 하는 부분을 주의
- > (gt), < (lt), >= (ge), <= (le), ! (not), == (eq), != (neq, ne)
- 조건식: 자바의 조건식과 유사
- Elvis 연산자(?:): 조건식의 편의 버전
- No-Operation: _ 인 경우 마치 타임리프가 실행되지 않는 것 처럼 동작, 이것을 잘 사용하면 HTML 의 내용 그대로 활용 가능
타임리프 태그 속성(Attribute)
- th:* 로 속성을 적용하면 기존 속성을 대체
<input type="text" name="mock" th:name="userA" />
// 타임리프 렌더링 후 <input type="text" name="userA" />
- 속성 추가
- th:attrappend : 속성 값의 뒤에 값을 추가
- th:attrprepend : 속성 값의 앞에 값을 추가
- th:classappend : class 속성에 자연스럽게 추가
- checked 처리
- 타임리프의 th:checked는 값이 false인 경우 checked 속성 자체를 제거
- <input type="checkbox" name="active" th:checked="false" />
- 타임리프 렌더링 후: <input type="checkbox" name="active" />
반복
- 타임리프에서 반복은 th:each 를 사용
// 오른쪽 컬렉션(${users})의 값을 하나씩 꺼내서 왼쪽 변수(user)에 담아서 태그를 반복
<tr th:each="user, userStat : ${users}">
<td th:text="${userStat.count}">username</td> // 반복의 두번째 파라미터를 설정해서 반복의 상태를 확인
<td th:text="${user.username}">username</td>
. . .
- 두번째 파라미터는 생략 가능한데, 생략하면 지정한 변수명(user) + Stat가 됨
주석
- 표준 HTML 주석
- 자바스크립트의 표준 HTML 주석은 타임리프가 렌더링 하지 않고, 그대로 남겨둠
- <!-- -->
- 타임리프 파서 주석
- 타임리프의 진짜 주석, 렌더링에서 주석 부분을 제거
- <!--/* [[${data}]] */-->
- 타임리프 프로토타입 주석
- HTML 주석에 약간의 구문을 더함
- 타임리프 렌더링을 거치면 이 부분이 정상 렌더링 (html 파일은 x)
- <!--/*/ /*/-->
블록
- <th:block>은 HTML 태그가 아닌 타임리프의 유일한 자체 태그
<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>
자바스크립트 인라인
- 타임리프는 자바스크립트에서 타임리프를 편리하게 사용할 수 있는 자바스크립트 인라인 기능을 제공
<script th:inline="javascript">
var username = [[${user.username}]]; // 인라인 사용 후 렌더링 결과를 보면 문자 타입인 경우 "를 포함
var age = [[${user.age}]];
//자바스크립트 내추럴 템플릿
var username2 = /*[[${user.username}]]*/ "test username"; // var username2 = "userA";
//객체
var user = [[${user}]]; // 객체를 JSON으로 자동으로 변환
</script>
<!-- 자바스크립트 인라인 each -->
<script th:inline="javascript">
[# th:each="user, stat : ${users}"]
var user[[${stat.count}]] = [[${user}]];
[/]
</script>
// var user1 = {"username":"userA","age":10};
템플릿 조각
- 여러 페이지에서 함께 사용하는 영역들을 효율적으로 코딩하기 위해 템플릿 조각과 레이아웃 기능을 지원
footer.html
<footer th:fragment="copy">
푸터 자리 입니다.
</footer>
<footer th:fragment="copyParam (param1, param2)">
<p>파라미터 자리 입니다.</p>
<p th:text="${param1}"></p>
<p th:text="${param2}"></p>
fragmentMain.html
<h1>부분 포함</h1>
<h2>부분 포함 insert</h2> <!-- 현재 태그( div ) 내부에 추가 -->
<div th:insert="~{template/fragment/footer :: copy}"></div>
<h2>부분 포함 replace</h2> <!-- 현재 태그( div )를 대체 -->
<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 ('데이터1', '데이터2')}"></div>
템플릿 레이아웃
- <head>에 공통으로 사용하는 css , javascript 같은 정보들을 한 곳에 모아두고 공통으로 사용하며, 각 페이지마다 필요한 정보를 더 추가해서 사용
base.html
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="common_header(title,links)">
<title th:replace="${title}">레이아웃 타이틀</title>
<!-- 공통 -->
<link rel="stylesheet" type="text/css" media="all" th:href="@{/css/awesomeapp.css}">
<link rel="shortcut icon" th:href="@{/images/favicon.ico}">
<script type="text/javascript" th:src="@{/sh/scripts/codebase.js}"></script>
<!-- 추가 -->
<th:block th:replace="${links}" />
</head>
layoutMain.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="template/layout/base :: common_header(~{::title},~{::link})">
<title>메인 타이틀</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
<link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}">
</head>
- common_header(~{::title},~{::link})
- ::title 은 현재 페이지의 title 태그들을 전달
- ::link 는 현재 페이지의 link 태그들을 전달
<head> 정도에만 적용하는게 아니라 <html> 전체에 적용
layoutFile.html
<!DOCTYPE html>
<html th:fragment="layout (title, content)" xmlns:th="http://
www.thymeleaf.org">
<head>
<title th:replace="${title}">레이아웃 타이틀</title>
</head>
<body>
<h1>레이아웃 H1</h1>
<div th:replace="${content}">
<p>레이아웃 컨텐츠</p>
</div>
<footer>
레이아웃 푸터
</footer>
</body>
</html>
layoutExtendMain.html
<!DOCTYPE html>
<html th:replace="~{template/layoutExtend/layoutFile :: layout(~{::title}, ~{::section})}"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>메인 페이지 타이틀</title>
</head>
<body>
<section>
<p>메인 페이지 컨텐츠</p>
<div>메인 페이지 포함 내용</div>
</section>
</body>
</html>
참고 강의:
스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 - 인프런 | 강의
웹 애플리케이션 개발에 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. MVC 2편에서는 MVC 1편의 핵심 원리와 구조 위에 실무 웹 개발에 필요한 모든 활용 기술들을 학습할 수 있
www.inflearn.com
'Spring Boot' 카테고리의 다른 글
Validation (0) | 2023.07.05 |
---|---|
Thymeleaf - 스프링 통합과 폼 (0) | 2023.07.04 |
Thymeleaf (0) | 2023.06.30 |
Spring Boot - MVC 기능 (0) | 2023.06.30 |
Spring Boot - MVC 구조 (0) | 2023.06.25 |