본문 바로가기

Programming/스프링

[김영한 스프링 MVC 2] 타임리프 - 기본 기능

타임리프

 

공식 사이트: https://www.thymeleaf.org/
공식 메뉴얼 - 기본 기능 : https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
공식 메뉴얼 - 스프링 통합 : https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html

 

 

  • 특징
  • 서버사이드 HTML 렌더링 (SSR)

백엔드 서버에서 HTML을 동적으로 렌더링

 

 

  • 내추럴 템플릿

순수 HTML을 유지해서 웹 브라우저에서 파일을 직접 열어도 내용 확인 가능

+

서버를 통해 뷰 템플릿을 거치면 동적으로 변경된 결과 확인 가능

 

 

  • 스프링 통합 지원

스프링과 자연스럽게 통합되고 스프링의 다양한 기능 편리하게 사용 가능

 

 

 

  • 기본 기능

사용 선언 : 

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

 

 

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

• 리터럴
◦ 텍스트: 'one text', 'Another one!',…
◦ 숫자: 0, 34, 3.0, 12.3,…
◦ 불린: true, false
◦ 널: null
◦ 리터럴 토큰: one, sometext, main,…

• 문자 연산:
◦ 문자 합치기: +
◦ 리터럴 대체: |The name is ${name}|

• 산술 연산:
◦ Binary operators: +, -, *, /, %
◦ Minus sign (unary operator): -

• 불린 연산:
◦ Binary operators: and, or
◦ Boolean negation (unary operator): !, not

• 비교와 동등:
◦ 비교: >, <, >=, <= (gt, lt, ge, le)
◦ 동등 연산: ==, != (eq, ne)

• 조건 연산:
◦ If-then: (if) ? (then)
◦ If-then-else: (if) ? (then) : (else)
◦ Default: (value) ?: (defaultvalue)

• 특별한 토큰:
◦ No-Operation: _

 

 

 

텍스트 - text, utext

 

  • 텍스트 출력
1. 태그 속성 이용
<span th:text="${data}">

2. 컨텐츠 안에서 직접 출력
<span>[[${data}]]</span>

 

 

  • BasicController
    @GetMapping("text-basic")
    public String textBasic(Model model){
        model.addAttribute("data", "Hello Spring!");

        return "basic/text-basic";
    }

 

 

 

  • text-basic.html
<!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>

 

 

 

  • Escape

: HTML에서 사용하는 특수 문자를 HTML 엔티티로 변경하는 것

 

웹 브라우저는 <를 HTML 태그의 시작으로 인식 → <를 문자로 표현하는 방법도 필요 => HTML 엔티티 

ex) <  →   &lt; 

타임리프 기능 th:text , [[...]] 는 이스케이프 기본 제공

 

 

 

  • Unescape

: 이스케이프 기능 비활성화

 

th:utext , [(...)] 

 

 

  • BasicController
    @GetMapping("text-unescaped")
    public String textUnescaped(Model model){
        model.addAttribute("data", "Hello <b>Spring!</b>");

        return "basic/text-unescaped";
    }

 

 

 

  • text-unescaped.html
<!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>

 

 

 

※ 실무에서 escape 사용하지 않아 HTML 정상 렌더링되지 않는 경우 많음 

escape 기본으로 하고 필요할 떄만 unescape 사용하기

 

 

 

변수 - SpringEL

 

변수 표현식
${...}

 

 

  • 다양한 표현식

Object
user.username : user의 username을 프로퍼티 접근 = user.getUsername()
user['username'] : 위와 같음 
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를 찾고 메서드 직접 호출

 

 

  • BasicController
    @GetMapping("/variable")
    public String variable(Model model){
        User userA = new User("userA", 10);
        User userB = new User("userB", 22);

        ArrayList<User> list = new ArrayList<>();
        list.add(userA);
        list.add(userB);

        HashMap<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";
    }
    
    @Data
    static class User {
        private String username;
        private int age;

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

 

 

  • variable.html
<!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>
</body>
</html>

 

 

  • 지연 변수 선언

지역 변수 선언 후, 선언한 태그 안에서만 사용

th:with

 

 

  • variable.html
<h1>지역 변수 - (th:with)</h1>
<div th:with="first=${users[0]}"> <!---->
  <p>처음 사람의 이름은 <span th:text="${first.username}"></span></p> <!---->
</div>

 

 

 

기본 객체들

 

기본 객체 :
${#locale}

편의 객체 :
${param.XXX} <!--HTTP 요청 파라미터 접근--> 
${session.XXX} <!--HTTP 세션 접근-->
${@helloBean.hello('Spring')} <!--스프링빈 접근-->

 

 

※ 스프링부트 3.0

스프링부트 3.0 부터는 ${#request} , ${#response} , ${#session} , ${#servletContext} 지원 X

직접 model에 해당 객체 추가해 사용해야 함

 

 

  • BasicController
    @GetMapping("/basic-objects")
    public String basicObjects(Model model, HttpServletRequest request,
                               HttpServletResponse response, HttpSession session) {
        session.setAttribute("sessionData", "Hello Session");

        model.addAttribute("request", request);
        model.addAttribute("response", response);
        model.addAttribute("servletContext", request.getServletContext());

        return "basic/basic-objects";
    }

    @Component("helloBean")
    static class HelloBean{
        public String hello(String data){
            return "Hello " + data;
        }
    }

 

 

  • basic-objects.html
<!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>

 

 

유틸리티 객체와 날짜

 

#message : 메시지, 국제화 처리
#uris : URI 이스케이프 지원
#dates : java.util.Date 서식 지원
#calendars : java.util.Calendar 서식 지원
#temporals : 자바8 날짜 서식 지원
#numbers : 숫자 서식 지원
#strings : 문자 관련 편의 기능
#objects : 객체 관련 기능 제공
#bools : boolean 관련 기능 제공
#arrays : 배열 관련 기능 제공
#lists , #sets , #maps : 컬렉션 관련 기능 제공
#ids : 아이디 처리 관련 기능 제공

 

 

타임리프 유틸리티 객체
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#expression-utility-objects

 

유틸리티 객체 예시
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expression-utility-object

 

  • temporals

 

  • BasicController
    @GetMapping("/date")
    public String date(Model model) {
        model.addAttribute("localDateTime", LocalDateTime.now());
        return "basic/date";
    }

 

 

  • date.html
<!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>

 

 

 

URL 링크

 

  • 링크

단순한 URL

@{/hello} 

=>

/hello

 

쿼리 파라미터

@{/hello(param1=${param1}, param2=${param2})}

=>

/hello?param1=data1&param2=data2

() 내부는 쿼리 파라미터로 처리됨

 

경로 변수

@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}

=>

/hello/data1/data2


URL 경로상에 변수가 있을 때 해당 () 부분은 경로 변수로 처리됨


경로 변수 + 쿼리 파라미터

@{/hello/{param1}(param1=${param1}, param2=${param2})}

=>

/hello/data1?param2=data2


경로 변수&쿼리 파라미터 함께 사용 가능

 

 

  • BasicController
    @GetMapping("link")
    public String link(Model model){
        model.addAttribute("param1", "data1");
        model.addAttribute("param2", "data2");

        return "basic/link";
    }

 

 

  • link.html
<!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>

 

 

 

리터럴

: 소스 코드상에 고정된 값

 

  • 타임리프 리터럴

문자: 'hello'
숫자: 10
불린: true , false
null: null

 

※ 문자 리터럴

항상 ' (작은 따옴표) 로 감싸야 함

but 공백 없이 쭉 이어진다면 작은 따옴표 생략 가능  
조건: A-Z , a-z , 0-9 , [] , . , - , _

ex) <span th:text="hello">

 

 

  • BasicController
    @GetMapping("literal")
    public String literal(Model model){
        model.addAttribute("data", "Spring!");

        return "basic/literal";
    }

 

 

  • literal.html
<!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>

 

 

※ 리터럴 대체

<span th:text="|hello ${data}|">

 

템플릿처럼 편리하게 텍스트 사용 가능

 

 

 

연산

 

  • 비교연산

HTML 엔티티 사용 권장 (>, < 는 must)

> (gt), < (lt), >= (ge), <= (le), ! (not), == (eq), != (neq, ne)

 

 

  • 조건식

 

 

  • Elvis 연산자 : 조건식의 편의 버전

ex) A?:B ⇒ A가 true면 A 표시, false면 B 표시

 

 

  • No-Operation

_ ⇒ 타임리프가 실행되지 않는 것처럼 동작 ex) A?:_ ⇒ A가 true면 A 표시, 아니면 기존 태그 그대로

 

 

  •  
@GetMapping("/operation")
public String operation(Model model) {
	model.addAttribute("nullData", null);
	model.addAttribute("data", "Spring!");
	return "basic/operation";
}

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<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>
</html>

 

 

 

속성 값 설정

th:XXX ⇒ 기존 속성 대체 (기존 속성 없으면 생성)

 

<input type="text" name="mock" th:name="userA" />
	
타임리프 렌더링 후 
<input type="text" name="userA" />

 

 

  • 속성 추가

th:attrappend : 속성 값의 뒤에 값 추가
th:attrprepend : 속성 값의 앞에 값 추가
th:classappend : class 속성에 자연스럽게 추가

 

 

  • checked 처리

HTML : checked=false 도 checked 처리 됨

타임리프(th:checked) : 값이 false 인 경우 checked 속성 자체를 제거

 

<input type="checkbox" name="active" th:checked="false" />

타임리프 렌더링 후
<input type="checkbox" name="active" />

 

 

  •  
@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:each

<tr th:each="user : ${users}">

 

List, 배열, java.util.Iterable, java.util.Enumeration 구현한 모든 객체 ⇒ 반복 사용 가능
Map도 사용 가능 ⇒ 변수에 담기는 값은 Map.Entry

 

 

  • 반복 상태
<tr th:each="user, userStat : ${users}">

반복의 두번째 파라미터 설정 ⇒ 반복 상태 확인
두번째 파라미터 생략 → 지정한 변수명 + Stat으로 자동 설정됨 (user + Stat = userStat)

 

  • 반복 상태 기능

index : 0부터 시작하는 값
count : 1부터 시작하는 값
size : 전체 사이즈
even , odd : 홀수, 짝수 여부( boolean )
first , last :처음, 마지막 여부( boolean )
current : 현재 객체

 

 

 

  •  
@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>

 

 

조건부 평가

if, unless

switch

 

  •  
    @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>

 

 

 

주석

 

1. 표준 HTML 주석

<!-- -->


자바스크립트의 표준 HTML 주석 => 타임리프가 렌더링하지 않고, 그대로 주석으로 표시됨

 


2. 타임리프 파서 주석

<!--/* */-->


타임리프 렌더링 시 주석 표시 안됨

 


3. 타임리프 프로토타입 주석

<!--/*/ /*/-->


HTML 파일으로 열었을 때 주석으로 처리

타임리프 렌더링 시 타임리프 태그로 표시됨

 

 

  •  
    @GetMapping("comments")
    public String comments(Model model){
        model.addAttribute("data", "Spring!");

        return "basic/comments";
    }

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<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}]] */-->
<!--/*-->
<span th:text="${data}">html data</span>
<!--*/-->
<h1>3. 타임리프 프로토타입 주석</h1> <!--타임리프 렌더링 시 주석 처리한 태그 표시됨-->
<!--/*/
<span th:text="${data}">html data</span>
/*/-->
</body>
</html>

 

=> 타임리프 렌더링 시

<h1>예시</h1>
<span>Spring!</span>
<h1>1. 표준 HTML 주석</h1>
<!--
<span th:text="${data}">html data</span>
-->
<h1>2. 타임리프 파서 주석</h1>
<h1>3. 타임리프 프로토타입 주석</h1>
<span>Spring!</span>

 

 

 

블록

th:block

타임리프의 유일한 자체 태그

 

=> 정의한 태그 속성을 여러 블록 (ex. <div> 태그)에서 활용할 때 사용

 

 

  •  
    @GetMapping("block")
    public String block(Model model){
        addUsers(model);

        return "basic/block";
    }

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<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>
</html>

 

 

 

자바스크립트 인라인
<script th:inline="javascript">

 

 

  •  
    @GetMapping("/javascript")
    public String javascript(Model model) {
        model.addAttribute("user", new User("userA", 10));
        addUsers(model);

        return "basic/javascript";
    }

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<!-- 자바스크립트 인라인 사용 전 -->
<script>
  var username = [[${user.username}]];
  var age = [[${user.age}]];

  //자바스크립트 내추럴 템플릿
  var username2 = /*[[${user.username}]]*/ "test username";

  //객체
  var user = [[${user}]];
</script>

<!-- 자바스크립트 인라인 사용 후 -->
<script th:inline="javascript">
  var username = [[${user.username}]];
  var age = [[${user.age}]];

  //자바스크립트 내추럴 템플릿
  var username2 = /*[[${user.username}]]*/ "test username";

  //객체
  var user = [[${user}]];
</script>


<!-- 자바스크립트 인라인 each -->
<script th:inline="javascript">
  [# th:each="user, stat : ${users}"]
  var user[[${stat.count}]] = [[${user}]];
  [/]
</script>
</body>
</html>

 

결과

<script>
var username = userA;
var age = 10;
//자바스크립트 내추럴 템플릿
var username2 = /*userA*/ "test username";
//객체
var user = BasicController.User(username=userA, age=10);
</script>

사용 후

<script>
var username = "userA";
var age = 10;
//자바스크립트 내추럴 템플릿
var username2 = "userA";
//객체
var user = {"username":"userA","age":10};
</script>

 

 

 

템플릿 조각

th:fragment

 

fragment로 정의된 태그 (템플릿 조각)을 다른 파일에서 사용 (insert, replace)

 

 

  • TemplateController
    @GetMapping("/fragment")
    public String template(){
        return "template/fragment/fragmentMain";
    }

 

 

  • fragmentMain.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<h1>부분 포함</h1>
<h2>부분 포함 insert</h2>
<div th:insert="~{template/fragment/footer :: copy}"></div> <!-- footer 파일의 copy라는 부분을 템플릿 조각으로 가져와 사용-->
<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 ('데이터1', '데이터2')}"></div>
</body>
</html>

 

 

  • footer.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <footer th:fragment="copy">
    푸터 자리입니다.
  </footer>

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

 

 

  • 결과

 

 

 

템플릿 레이아웃

 

레이아웃 구축, 필요한 코드 조각 전달

 

 

  • layoutMain.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="template/layout/base :: common_header(~{::title},~{::link})"> <!--현 페이지 title, link 태그들 전달, 해당 결과로 replace-->
  <title>메인 타이틀</title>
  <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
  <link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}">
</head>
<body>
메인 컨텐츠
</body>
</html>

 

 

  • 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>

 

 

  • 결과
<html>
<head>
<title>메인 타이틀</title> <!---->
<!-- 공통 -->
<link rel="stylesheet" type="text/css" media="all" href="/css/awesomeapp.css">
<link rel="shortcut icon" href="/images/favicon.ico">
<script type="text/javascript" src="/sh/scripts/codebase.js"></script>
<!-- 추가 -->
<link rel="stylesheet" href="/css/bootstrap.min.css"> <!---->
<link rel="stylesheet" href="/themes/smoothness/jquery-ui.css"> <!---->
</head>
<body>
메인 컨텐츠
</body>
</html>



 

템플릿 레이아웃2

 

  • layoutMain.html
<!DOCTYPE html>
<html th:replace="~{template/layoutExtend/layoutFile :: layout(~{::title}, ~{::section})}"
      xmlns:th="http://www.thymeleaf.org"> <!--현페이지 title, section 전달보내고, 파라미터 반영된 layoutFile로 대체-->
<head>
  <title>메인 페이지 타이틀</title>
</head>
<body>
<section>
  <p>메인 페이지 컨텐츠</p>
  <div>메인 페이지 포함 내용</div>
</section>
</body>
</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>

 

 

  • 결과
<!DOCTYPE html>
<html>
  <head>
    <title>메인 페이지 타이틀</title> <!---->
  </head>
  <body>
    <h1>레이아웃 H1</h1>
    <section>
      <p>메인 페이지 컨텐츠</p> <!---->
      <div>메인 페이지 포함 내용</div> <!---->
  </section>
  <footer>
    레이아웃 푸터
  </footer>
  </body>
</html>