
스프링 부트 스타터 사이트로 이동해서 프로젝트 생성
✔️ 프로젝트 선택
✔️ Project Metadata
✔️ Dependencies
✔️ 타임리프 특징
1️⃣ 서버 사이드 HTML 렌더링 (SSR)
2️⃣ 네츄럴 템플릿
3️⃣ 스프링 통합 지원
✔️ 타임리프 사용 선언
타임리프를 사용하려면 다음 선언을 하면 된다!
`<html xmlns:th="http://www.thymeleaf.org">`
타임리프의 가장 기본 기능인 텍스트를 출력하는 기능 먼저 알아보자😊
HTML의 콘텐츠(content)에 데이터를 출력할 때는 th:text 를 사용하면 된다.
➡️ <span th:text="${data}">
   @Controller
  @RequestMapping("/basic")
  public class BasicController {
      @GetMapping("/text-basic")
      public String textBasic(Model model) {
          model.addAttribute("data", "Hello Spring!");
          return "basic/text-basic";
      }
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>컨텐츠에 데이터 출력하기</h1>
<ul>
  <li>th:text 사용 <span th:text="${data}"></span></li>
  <li>컨텐츠 안에서 직접 출력하기 = [[${data}]]</li>
</ul>
</body>
</html>
@GetMapping("/text-unescaped")
  public String textUnescaped(Model model) {
      model.addAttribute("data", "Hello <b>Spring!</b>");
      return "basic/text-unescaped";
  }
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<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>
</html>
HTML문서는 <,> 같은 특수문자를 기반으로 정의된다.
따라서 뷰 템플릿으로 HTML 화면을 생성할 때는 출력하는 데이터에 이러한 특수 문자가 있는 것을 주의해서 사용해야 한다!!
웹 브라우저는 < 를 HTML 태그의 시작으로 인식한다.
따라서 <를 태그의 시작이 아니라 문자로 표현할 수 있는 방법이 필요한데, 이것을 HTML 엔티티라 한다❗️
그리고 이렇게 HTML에서 사용하는 특수 문자를 HTML 엔티티로 변경하는 것을 이스케이프(escape) 라 한다.
그리고 타임리프가 제공하는 th:text , [[...]] 는 기본적으로 이스케이스(escape)를 제공한다.
<  ➡️ < >  ➡️ >이스케이프 기능을 사용하지 않으려면 어떻게 해야할까🤔❓
타임리프는 다음 두 기능을 제공한다❗️
th:text ➡️ th:utext[[...]] ➡️ [(...)]타임리프에서 변수를 사용할 때는 변수 표현식을 사용한다.
➡️  ${...}
@GetMapping("/variable")
    public String variable(Model model) {
        User userA = new User("userA", 10);
        User userB = new User("userB", 20);
        List<User> list = new ArrayList<>();
        list.add(userA);
        list.add(userB);
        Map<String, User> map = new HashMap<>();
        map.put("userA", userA);
        map.put("userB", userB);
        model.addAttribute("user", userA);
        model.addAttribute("users", list);
        model.addAttribute("userMap", map);
        return "basic/variable";
    }
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>SpringEL 표현식</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>
<h1>지역 변수 - (th:with)</h1>
<div th:with="first=${users[0]}">
    <p>처음 사람의 이름은 <span th:text="${first.username}"></span></p>
</div>
</body>
</html>
Object
user.username : user의 username을 프로퍼티 접근 ➡️ user['username']user['username'] : 위와 같음 ➡️ user.getUsername()user.getUsername() : user의 getUsername() 을 직접 호출List
users[0].username : List에서 첫 번째 회원을 찾고 username 프로퍼티 접근 ➡️ list.get(0).getUsername()users[0]['username']: 위와 같음users[0].getUsername() : List에서 첫 번째 회원을 찾고 메서드 직접 호출Map
userMap['userA'].username : Map에서 userA를 찾고, username 프로퍼티 접근 ➡️ map.get("userA").getUsername()userMap['userA']['username'] : 위와 같음 userMap['userA'].getUsername() : Map에서 userA를 찾고 메서드 직접 호출📌 지역 변수 선언
th:with를 사용하면 지역 변수를 선언해서 사용할 수 있다.
지역 변수는 선언한 테그 안에서만 사용할 수 있다.
타임리프는 기본 객체들을 제공한다❗️
${#request}${#response}${#session} ${#servletContext} ${#locale}그런데 #request 는 HttpServletRequest 객체가 그대로 제공되기 때문에 데이터를 조회하려면 request.getParameter("data") 처럼 불편하게 접근해야 한다😐
이런 점을 해결하기 위해 편의 객체도 제공한다👍🏻
param${param.paramData}session${session.sessionData}@${@helloBean.hello('Spring!')}@GetMapping("/basic-objects")
  public String basicObjects(HttpSession session) {
      session.setAttribute("sessionData", "Hello Session");
      return "basic/basic-objects";
  }
  @Component("helloBean")
  static class HelloBean {
      public String hello(String data) {
          return "Hello " + data;
} 
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>식 기본 객체 (Expression Basic Objects)</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>
<h1>편의 객체</h1>
<ul>
    <li>Request Parameter = <span th:text="${param.paramData}"></span></li>
    <li>session = <span th:text="${session.sessionData}"></span></li>
    <li>spring bean = <span th:text="${@helloBean.hello('Spring!')}"></span></li>
</ul>
</body>
</html>
타임리프는 문자, 숫자, 날짜, URI등을 편리하게 다루는 다양한 유틸리티 객체들을 제공한다!
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<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>
<h1>LocalDateTime - Utils</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.monthNameShort(localDateTime)} = <span th:text="${#temporals.monthNameShort(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.dayOfWeekNameShort(localDateTime)} = <span th:text="${#temporals.dayOfWeekNameShort(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>
    <li>${#temporals.nanosecond(localDateTime)} = <span th:text="${#temporals.nanosecond(localDateTime)}"></span></li>
</ul>
</body>
</html>
✔️ 타임리프 유틸리티 객체들
#message : 메시지, 국제화 처리#uris : URI 이스케이프 지원#dates : java.util.Date 서식 지원 #calendars : java.util.Calendar 서식 지원#temporals : 자바8 날짜 서식 지원#numbers : 숫자 서식 지원#strings : 문자 관련 편의 기능#objects : 객체 관련 기능 제공#bools : boolean 관련 기능 제공#arrays : 배열 관련 기능 제공#lists , #sets , #maps : 컬렉션 관련 기능 제공#ids : 아이디 처리 관련 기능 제공, 뒤에서 설명타임리프에서 자바8 날짜인
LocalDate,LocalDateTime,Instant를 사용하려면 추가 라이브러리가 필요하다.
스프링 부트 타임리프를 사용하면 해당 라이브러리가 자동으로 추가되고 통합된다👍🏻
➡️ 타임리프 자바 8 날짜 지원 라이브러리 :thymeleaf-extras-java8time
타임리프에서 URL을 생성할 때는 @{...} 문법을 사용하면 된다!
@GetMapping("/link")
  public String link(Model model) {
      model.addAttribute("param1", "data1");
      model.addAttribute("param2", "data2");
      return "basic/link";
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>URL 링크</h1>
<ul>
    <li><a th:href="@{/hello}">basic url</a></li>
    <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>
</ul>
</body>
</html>
✔️ 단순한 URL
@{/hello}➡️ /hello✔️ 쿼리 파라미터
@{/hello(param1=${param1}, param2=${param2})}/hello?param1=data1¶m2=data2✔️ 경로 변수
@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}/hello/data1/data2✔️ 경로 변수 + 쿼리 파라미터
@{/hello/{param1}(param1=${param1}, param2=${param2})}/hello/data1?param2=data2리터럴은 소스 코드상에 고정된 값을 말하는 용어이다.
예를 들어서 아래 코드에서 "Hello" 는 문자 리터럴, 10 , 20 는 숫자 리터럴이다.
String a = "Hello"
int a = 10 * 20
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<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>
</body>
</html>
'hello' 10true , false null타임리프에서 문자 리터럴은 항상 ' (작은 따옴표)로 감싸야 한다❗️
<span th:text="hello world!"></span> ➡️ 오류
<span th:text="'hello world!'"></span> ➡️ 정상 동작
@GetMapping("/literal")
         
   public String literal(Model model) {
      model.addAttribute("data", "Spring!");
      return "basic/literal";
}
타임리프 연산은 자바와 크게 다르지 않다.
HTML안에서 사용하기 때문에 HTML 엔티티를 사용하는 부분만 주의하자❗️
 @GetMapping("/operation")
  public String operation(Model model) {
      model.addAttribute("nullData", null);
      model.addAttribute("data", "Spring!");
      return "basic/operation";
}
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<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">변수 - SpringEL</a></li>
            <li><a href="/basic/basic-objects?paramData=HelloParam">기본 객체들</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">유연한 레이아웃</a></li>
            <li><a href="/template/layoutExtend">레이아웃 상속</a></li>
        </ul>
    </li>
</ul>
</body>
</html>
타임리프는 주로 HTML 태그에 th:* 속성을 지정하는 방식으로 동작한다.
th:* 로 속성을 적용하면 기존 속성을 대체하고, 기존 속성이 없으면 새로 만든다.
@GetMapping("/attribute")
  public String attribute() {
      return "basic/attribute";
  }
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<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 o <input type="checkbox" name="active" th:checked="true" /><br/>
- checked x <input type="checkbox" name="active" th:checked="false" /><br/>
- checked=false <input type="checkbox" name="active" checked="false" /><br/>
</body>
</html>
th:attrappend : 속성 값의 뒤에 값을 추가한다. th:attrprepend : 속성 값의 앞에 값을 추가한다. th:classappend : class 속성에 자연스럽게(?) 추가한다.HTML에서는 <input type="checkbox" name="active" checked="false" /> ➡️ 이 경우에도  checked 속성이 있기 때문에 checked 처리가 되어버린다.
타임리프의 th:checked 는 값이 false 인 경우 checked 속성 자체를 제거한다!
<input type="checkbox" name="active" th:checked="false" /> ➡️ <input type="checkbox" name="active" />
타임리프에서 반복은 th:each 를 사용한다.
추가로 반복에서 사용할 수 있는 여러 상태 값을 지원한다!
 @GetMapping("/each")
   public String each(Model model) {
      addUsers(model);
      return "basic/each";
}
  private void addUsers(Model model) {
      List<User> list = new ArrayList<>();
      list.add(new User("userA", 10));
      list.add(new User("userB", 20));
      list.add(new User("userC", 30));
      model.addAttribute("users", list);
  }
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<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>
<h1>반복 상태 유지</h1>
<table border="1">
  <tr>
    <th>count</th>
    <th>username</th>
    <th>age</th>
    <th>etc</th>
  </tr>
  <tr th:each="user, userStat : ${users}">
    <td th:text="${userStat.count}">username</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>
</html>
<tr th:each="user : ${users}"> ➡️ 반복시 오른쪽 컬렉션(${users})의 값을 하나씩 꺼내서 왼쪽 변수(user)에 담아서 태그를 반복 실행한다.
📌 반복 상태 유지
<tr th:each="user, userStat : ${users}">
반복의 두번째 파라미터를 설정해서 반복의 상태를 확인할 수 있다.
두번째 파라미터는 생략 가능한데, 생략하면 지정한 변수명(user)+Stat이 된다.
✔️ 타임리프의 조건식
ifunless(if의 반대)@GetMapping("/condition")
  public String condition(Model model) {
      addUsers(model);
      return "basic/condition";
  }
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>if, unless</h1>
<table border="1">
    <tr>
        <th>count</th>
        <th>username</th>
        <th>age</th>
    </tr>
    <tr th:each="user, userStat : ${users}">
        <td th:text="${userStat.count}">1</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}"></span>
            <span th:text="'미성년자'" th:unless="${user.age ge 20}"></span>
        </td>
    </tr>
</table>
<h1>switch</h1>
<table border="1">
    <tr>
        <th>count</th>
        <th>username</th>
        <th>age</th>
    </tr>
    <tr th:each="user, userStat : ${users}">
        <td th:text="${userStat.count}">1</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>
</html>
타임리프는 해당 조건이 맞지 않으면 태그 자체를 렌더링하지 않는다!

히히 타임리프 쫌 재밌는데 ?