thymeleaf 템플릿 엔진
<html xmlns:th="http://www.thymeleaf.org">
<!DOCTYPE HTML>아래에 위 태그를 삽입한다. 템플릿 처리에는 영향을 미치지 않지만, 우리 IDE가 모든 th:* 속성에 대한 네임스페이스 정의가 부족하다고 불평하는것을 방지하는 역할이다.
1. thymeleaf 표준 표현 문법
문서: https://www.thymeleaf.org/doc/tutorials/3.1/usingthymeleaf.html#standard-expression-syntax
● 간단 표현
○ 변수 표현식: ${...}
○ 선택 변수 표현식: *{...}
○ 메시지 표현식: #{...}
○ 링크 URL 표현식: @{...}
○ 부분 표현식: ~{...}
● 문자 그대로의
○ 텍스트 리터럴: 'one text', 'Another one!', ...
○ 숫자 리터럴: 0, 34, 3.0, 12.3, ...
○ Boolean 리터럴: true, false
○ Nul 리터럴: null
○ 리터럴 토큰: one, sometext, main, ...
● 텍스트 연산
○ 문자열 연결: +
○ 리터럴 대체: |The name is ${name}|
● 산술 연산
○ 2항 연산: +, -, *, /, %
○ 마이너스 기호: -
● Boolean 연산
○ 2항 연산: and, or
○ 부정: !, not
● 비교와 동등
○ 비교: >, <, >=, <= (gt, lt, ge, le)
○ 동등 연산: ==, != (eq, ne)
● 조건 연산
○ If-then: (if) ? (then)
○ If-then-else: (if) ? (then) : (else)
○ Default: (value) ?: (defaultvalue)
● 특별한 토큰
○ No-Operation: _
th:text는 escape를 하고 th:utext는 escape를 하지 않는다.
html 태그 속성이 아니라 직접 데이터를 출력하고싶다면 [[...]]을 사용한다.
예) [[${data}]]
자바스크립트 인라인을 사용하려면 <scirpt th:inline="javascript">을 사용한다. 그러면 문자열에 자동으로 따옴표를 넣어주고, 문제가 될 수 있는 문자는 이스케이프 처리를 해주고, 객체를 json으로 바꿔준다.
<script th:inline="javascript">
let username = [[${user.username}]]
let age = [[${user.age}]]
let user = [[${user}]]
</script>
href와 onlick="location.href= ' ' "
<a th:text="${item.itemName}" th:href="@{|/basic/items/${item.id}|}">테스트 상품1</a>
<button th:onclick="|location.href='@{|/basic/items/add/${item.id}|}'|"
type="button">상품 등록</button>
url parameter를 가져오고싶다면 ${param.status} 처럼 param으로 가져올 수 있다.
<h2 th:if="${param.status}" th:text="'저장 완료!'"></h2>
2. thymeleaf 반복
문서: https://www.thymeleaf.org/doc/tutorials/3.1/usingthymeleaf.html#iteration
java.util.Iterable, java.util.Enumeration, java.util.Iterator, java.util.Map, java.util.stream.Stream과 배열은 th:each로 반복할 수 있다.
th:each부분의 "people : ${peoples}"를 보면 for Each문법과 같다.
3. thymeleaf 조건 평가
문서: https://www.thymeleaf.org/doc/tutorials/3.1/usingthymeleaf.html#conditional-evaluation
th:if와 th:unless를 사용할 수 있다.
예를들어, 세션 정보를 확인해 로그인이 되어있을 때 메인화면과 로그인이 안되어있을 때 메인화면 표시를 다르게 한다.
여기서는 data에 임의의 정보를 넣어 세션이라고 가정해본다.
4. thymeleaf spring 통합과 폼
타임리프는 스프링과 함께 사용되어 편리하게 제공하는 것들이 있다.
문서: https://www.thymeleaf.org/doc/tutorials/3.1/thymeleafspring.html
편리한 폼 관리를 위해 th:object th:field th:errors th:errorclass를 제공한다.
th:object는 폼 커맨드 선택을 해 하위 돔에서 선택 변수 표현식: *{...}을 사용할 수 있게 한다.
th:field는 id, name, value속성을 자동으로 넣어준다. 단일 체크박스에서 사용될 때는 히든필드까지 자동 생성한다.