쿠릉쿠릉 쾅쾅
쿠릉쿠릉 쾅쾅
쿠릉쿠릉 쾅쾅
250x250
전체 방문자
오늘
어제
  • 분류 전체보기
    • HTML CSS
    • 잡담
    • 프로그래밍 꿀팁 사이트
    • 코딩 도서
    • [자바]
      • 디자인 패턴
      • 자바의 정석 - 3판
      • 자바
      • 자바 문법
    • git
    • [TDD]
    • 개발 서적 독후감
      • 클린 코더
      • 토비 스프링3
      • 객체지향의 사실과 오해
      • 모던 자바 인 액션
      • 엘레강트 오브젝트
    • CS
      • 운영체제
      • HTTP
    • [SQL]
      • SQL 기초
      • 혼자공부하는SQL
    • [ Spring ]
      • REST API
      • Spring Toy
      • Spring 에러
      • Spring
      • Spring 입문
      • Spring 핵심 원리
      • SpringMVC 1편
      • SpringMVC 2편
      • Spring Boot를 이용한 RESTful We..
      • Batch
    • [JPA]
      • JPA
      • JPA 에러
      • JPA 프로그래밍 - 기본편
      • 스프링 부트와 JPA 활용 1 - 웹 애플리케이..
      • 실전! 스프링 부트와 JPA 활용2 - API 개..
      • 실전! 스프링 데이터 JPA
      • 실전! Querydsl
    • 인텔리제이
    • [DB]
      • DB
      • H2
    • Gradle
    • 면접
    • [알고리즘]
      • 알고리즘
      • 자료구조
      • 자바 알고리즘 공부
    • [프로젝트]
    • 쿠릉식 객체지향 사고
    • 리눅스

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • http
  • MVC
  • Spring
  • SQL
  • 스프링부트
  • querydsl
  • 스프링
  • 자료구조
  • 재귀
  • JPA
  • Git
  • 깃허브
  • REST API
  • 백준
  • springboot
  • java
  • 알고리즘
  • 함수형인터페이스
  • 자바
  • GitHub

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
쿠릉쿠릉 쾅쾅

쿠릉쿠릉 쾅쾅

[Spring] Thymeleaf 타임리프 - 기본 기능
[ Spring ]/SpringMVC 2편

[Spring] Thymeleaf 타임리프 - 기본 기능

2022. 3. 2. 23:09
728x90

  

 

Thymeleaf 타임리프

 

🔍 타임리프 특징

  • 서버 사이드 HTML 렌더링 (SSR)
  • 네츄럴 템플릿
  • 스프링 통합지원

 

💡 서버 사이드 HTML 렌더링 (SSR)

  • 타임리프는 백엔드 서버에서 HTML을 동적으로 렌더링 하는 용도로 사용된다.

 

💡 네츄럴 템플릿

  • 타임리프는 순수 HTML을 최대한 유지하려는 특징이 있다.
  • 타임리프로 작성한 파일은 HTML을 유지하기 때문에 웹 브라우저에서 파일을 직접 열어도 내용을 확인할 수 있고, 서버를 통해 뷰 템플릿을 거치면 동적으로 변경된 결과를 확인할 수 있다.
  • JSP를 포함한 다른 뷰 템플릿은 파일 자체를 그대로 웹 브라우저에서 열면 JSP 소스 코드와 HTML이 뒤죽박죽 섞여서 웹 브라우저에서 정상적인 HTML 결과를 확인할 수 없다. 오직 서버를 통해서 JSP가 렌더링 되고 HTML 응답결과를 받아야 화면을 확인할 수 있다.
  • 타임리프는 작성된 파일을 그대로 웹 브라우저에서 열어도 정상적인 HTML 결과를 확인할 수 있다. 물론 이 경우 동적인 결과로  렌더링 되지는 않는다.
  • 이렇게 순수 HTML을 그대로 유지하면서 뷰 템플릿을 사용할 수 있는 타임리프의 특징을 네츄럴 템플릿(natural templates)이라고 한다.

 

💡 스프링 통합 지원

  • 타임리프는 스프링의 다양한 기능을 편리하게 사용할 수 있게 지원한다.

 

 

🔍 타임리프 사용 선언

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

 

 


 

 

Thymeleaf 타임리프 기능

 

🔍 기본 표현식

  • 간단한 표현 
    • 변수 표현식 : ${...}
    • 선택 변수 표현식 : *{...}
    • 메시지 표현식 : #{...}
    • 링크 URL 표현식 : @{...}
    • 조각 표현식 : ~{...}
  • 리터럴
    • 텍스트 : 'one text', 'Another one!', ....
    • 숫자 : 0, 34, 3.0, 12.3, ....
    • 불린 : true, fasle
    • 널 : 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

  • th:text는 자동적으로 이스케이프가 적용된다.
    • 웹 브라우저는 '<' 를 HTML 태그의 시작으로 인식한다. 따라서 '<' 를 태그의 시작이 아니라 문자로 표현할 수 있는 방법이 필요한데 이 것을 HTML 엔티티라고 한다.
    • HTML에서 사용하는 특수문자를 HTML 엔티티로 변경하는 것을 이스케이프(escape)라고 한다.
  • th:utext는 이스케이프 기능을 사용하지 않을 때 사용한다.

 

💡 text

  • HTML의 컨텐츠에 데이터를 출력할 때는 th:text를 사용하면 된다.
    • 예) <span th:text="${data}"></span>
  • HTML 태그의 속성이 아니라 HTML 컨텐츠 영역안에서 직접 데이터를 출력하고 싶으면 [[...]]를 사용하면 된다.
    • 예) [[${data}]]

 

📌 컨트롤러

@GetMapping("text-basic")
public String textBasic(Model model) {
    model.addAttribute("data", "HelloSpring!");
    return "/basic/text-basic";
}

 

📌 HTML

<ul>
    <li>th:text 사용 <span th:text="${data}"></span></li>
    <li>컨텐츠 안에서 직접 출력하기 = [[${data}]]</li>
</ul>

 

📌출력 결과 

 

💡 utext

  • HTML의 컨텐츠에 데이터를 출력할 때는 th:utext를 사용하면 된다.
    • 예) <span th:utext="${data}"></span>
  • HTML 태그의 속성이 아니라 HTML 컨텐츠 영역안에서 직접 데이터를 출력하고 싶으면 [(...)]를 사용하면 된다.
    • 예) [(${data})]

 

📌 컨트롤러

@GetMapping("text-unescaped")
public String textUnescaped(Model model) {
    model.addAttribute("data", "Hello<b>Spring</b>");
    return "basic/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>

 

📌 출력 결과

 

 

🔍 변수 표현식

  • 기본 변수 표현식 : ${...}

 

📌 컨트롤러

@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";
}

@Data
static class User {
    private String username;
    private int age;

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

 

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

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

</div>
</body>
</html>
  • 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'] → list.get(0).getUsername()
      • users[0].getUsername() : List에서 첫 번째 회원을 찾고 메서드를 직접 호출
    • Map
      • userMap['userA'].username : Map에서 userA를 찾고, username 프로퍼티 접근 → map.get("userA").getUsername()
      • userMap['userA']['username'] → map.get("userA").getUsername()
      • userMap['userA'].getUsername() : Map에서 userA를 찾고 메서드를 직접 호출
  • 지역 변수 선언
    • th:with를 사용하면 지역 변수를 선언해서 사용할 수 있다.
    • 지역 변수는 선언한 태그 안에서만 사용할 수 있다.

 

 

🔍 기본 객체

  • 타임리프는 기본 객체를 제공한다.
  • ${#request}
  • ${#response}
  • ${#session}
  • ${#servletContext}
  • ${#locale}

 

💡 기본객체에 대한 접근 편의 메서드

  • 기본 객체들의 프로퍼티 접근을 위해 편의 메서드를 제공한다.
    • request.getParameter("data") 이런식으로 호출을 해야하지만, 타임 리프에서는 편리하게 조회 호출 가능
  • HTTP 요청 파라미터 접근 : param
    • 예) ${param.paramData}
  • HTTP 세션 접근 : session
    • 예) ${session.sessionData}
  • 스프링 빈 접근 : @
    • 예) ${@helloBean.hello('Data')}

 

📌 컨트롤러

@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;
    }
}

 

📌 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>
  • 'http://localhost:8080/basic/basic-objects?paramData=HelloParam' URL 접속
  • ${param.paramData} 를 통해 요청 파라미터 접근
  • ${session.sessionData} 를 통해 HTTP 세션 접근
  • ${@helloBean.hello('Spring!')} 을 통해 스프링 빈 접근

 

 

🔍 유틸리티 객체와 날짜

  • 타임리프는 문자, 숫자, 날짜, URI 등을 편리하게 다루는 다앙한 유틸리티 객체들을 제공한다.

 

💡 타임리프 유틸리티 객체

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

유틸리티 객체 예시

  • https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expressionutility-objects

 

📌 컨트롤러

@GetMapping("/date")
public String data(Model model) {
    model.addAttribute("localDateTime", LocalDateTime.now());
    return "basic/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="${#taemporals.yer(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>
  • <span th:text="${#temporals.format(localDateTime,'yyyy-MM-dd HH:mm:ss')}"></span> 이런 형태로 자주 쓰인다.
    •  출력 예시 : 2022-03-03 09:26:28

 

 

🔍 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

 

💡 상대 경로, 절대 경로

  • /hello : 절대 경로
  • hello : 상대 경로
  • 잠고: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#link-urls

 

📌 컨트롤러

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

    return "basic/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>

    <!-- http://localhost:8080/hello?param1=data1&param2=data2 -->
    <li><a th:href="@{/hello(param1=${param1}, param2=${param2})}">hello query param</a></li>

    <!-- http://localhost:8080/hello/data1/data2 -->
    <li><a th:href="@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}">path variable</a></li>

    <!-- http://localhost:8080/hello/data1?param2=data2 -->
    <li><a th:href="@{/hello/{param1}(param1=${param1}, param2=${param2})}">path variable + query parameter</a></li>
</ul>
</body>
</html>

 

 

🔍  리터럴

  • 리터럴이란, 소스 코드상에 고정된 값을 말하는 용어다.
  • 타임리프에서 문자 리터럴은 항상 ' (작은 따옴표)로 감싸야 한다.
    • 예) <span th:text="'hello'"></span>
  • 그런데 문자를 항상 ' (작은 따옴표)로 감싸는 것은 귀찮기 때문에 공백 없이 쭉 이어진다면 하나의 의미있는 토큰으로 인지해서 작은 따옴표를 생략할 수 있다.
    • 룰 : A-Z, a-z, 0-9, [], ., -, _
    • 예) <span th:text="hello"></span>
    • 오류
      • 예) <span th:text="hello world!"></span>
      • 중간에 공백이 있어서 하나의 의미있는 토큰으로 인식되지 않아서 오류를 일으킨다.
      • <span th:text="'hello world!'"></span>처럼 중간에 공백이 있을 경우 작음 따옴표를 생략할 수 없다.
  • 리터럴 대체
    • 예) <span th:text="|hello ${data}|"></span>
    • 마지막의 리터럴 대체 문법을 사용하면 마치 템플릿을 사용한 것처럼 편하다.

 

📌 컨트롤러

@GetMapping("/literal")
public String literal(Model model) {
    model.addAttribute("data", "Spring!");
    return "basic/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>

 

 

🔍 연산

  • 타임리프의 연산은 자바의 연산과 차이가 없다.
  • 다만 HTML 안에서 사용하기 때문에 HTML 엔티티를 사용하는 부분은 주의해서 사용 할 것

 

💡 연산자 종류

  • 비교 연산자
    • > (gt)
    • < (lt)
    • >= (ge)
    • <= (le)
    • ! (not)
    • == (eq)
    • != (neq, ne)
  • 조건식 : 자바의 조건식과 유사하다.
    • 삼항 연산자 예) (10%2==0) ?  '짝' : '홀'
  • Elvis 연산자 : 조건식의 편의 버전
    • 예) $(data) ?: 'defaultValue'
    • data 값이 존재하면 data 값이 나오고, 존재하지 않으면 defaultValue 문자가 출력된다.
  • No-Operation : _ 인 경우 타임리프가 실행되지 않는 것 처럼 동작한다.
    • 예) <p th:text="$(nullData)?:_">defaultValue</p>

 

📌 컨트롤러

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

 

📌 HTML

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

 

 

🔍 속성 값

  • 타임리프는 주로 HTML 태그에 th:* 속성을 지정하는 방식으로 동작한다.
  • th:* 속성을 적용하면 기존 속성을 대체한다.
  • th:attrappend : 속성 값 뒤에 값을 추가한다.
  • th:attrprepend : 속성 값의 앞에 값을 추가한다.
  • th:classappend : class 속성에 자연스럽게 추가한다.
    • 이 방식이 많이 쓰인다.
  • checked 처리
    • HTML에서 checked 속성은 checked 속성의 값과 상관없이 checked라는 속성이 존재하기만 해도 체크가 된다.
    • 하지만 타임리프에서는 th:check 값이 false인 경우 checked 속성이 제거된다. true인 경우에는 존재하게 된다.

 

📌 컨트롤러

@GetMapping("/attribute")
public String attribute() {
    return "basic/attribute";
}

 

📌 HTML

<!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 : 속성 값 뒤에 값을 추가한다.
    • class=text large
  • th:attrprepend : 속성 값의 앞에 값을 추가한다.
    • cless=large text
  • th:classappend : class 속성에 자연스럽게 추가한다.
    • class=text large
    • 이 방식이 많이 쓰인다.
  • checked 처리
    • th:checked="false"인 경우 checked 속성을 지워버린다.
    • <input type="checkbox" name="active" th:checked="false"/>
    • → 타임리프 렌더링 후 : <input type="checkbox" name="active"/>

 

 

🔍 반복 기능

  • th:each 사용
  • 예) <tr th:each="user : ${users}">
    • 반복시 컬렉션인 ${users}의 값을 하나씩 꺼내서 변수 user에 담아서 태그를 반복 실행한다.
    • th:each는 List뿐만 아니라 배열, Iterable, Enumeration 을 구현한 모든 객체를 사용할 수 있다. Map도 사용할 수 있는데, 이 경우 변수에 담기는 값은 Map.Entry다.
  • 예) <tr th:each "user, userStat : ${users}">
    • 반복의 두 번째 파라미터를 설정해서 반복의 상태를 확인할 수 있다.
    • 두 번째 파라미터인 userStat는 생략이 가능하다. 생략할 경우 지정한 변수명(user) + 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);
}

 

📌 HTML

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

 

 

🔍 조건식

  • 타임 리프의 조건식 → 해당 조건에 맞지 않으면(조건식이 false인 경우) 태그 자체를 렌더링하지 않는다.  
    • th:if
    • th:unless (if의 반대)
  • switch-case문
<div th:switch="${조건대상 변수}">
    <span th:case="비교변수1">value1</span>
    <span th:case="비교변수2">value2</span>
    <span th:case="*">default</span>
</div>
  • *는 만족하는 조건이 없을 때 사용하는 디폴트다.

 

📌컨트롤러

@GetMapping("/condition")
public String condition(Model model) {
    addUsers(model);
    return "basic/condition";
}

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);
}

 

📌 HTML

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

 

 

🔍 주석

 

💡 HTML 기본 주석

<!-- <span th:text="${data}"html data></span> -->
  • Format : <!-- contents -->

 

💡 타임리프 파서 주석

  • 타임리프에 적용되는 주석으로 해당 주석 내용은 렌더링에서 주석 부분이 제거된다.
  • 제일 많이 사용된다.
  • Format 
    • 1줄 주석 : <!--/* contents */-->
    • 여러 줄 주석 : <!--/*--> contents <!--*/-->
<!--/* [[${data}]] */-->

<!--/*-->
<span th:text="${data}">html data</span>
<!--*/-->

 

💡 타임리프 프로토 타입 주석

  • HTML 파일을 그대로 열면 렌더링되지 않고 타임리프를 렌더링 한 경우에만 보이는 주석
  • Format
    • <!--/*/ contents /*/-->
<!--/*/
<span th:text="${data}">html data</span> 
/*/-->

 

 

 

📌 컨트롤러

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

 

📌 HTML

<!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>
  • 표준 HTML 주석
    • 자바스크립트의 표준 HTML 주석은 타임리프가 렌더링 하지 않고 그대로 남겨둔다.
  • 타임리프 파서 주석
    • 타임리프 파서 주석은 타임리프의 진짜 주석이다. 렌더링에서 주석 부분을 제거한다.
  • 타임리프 프로토타입 주석
    • 타임리프 프로토타입은 약간 특이한데, HTML 주석에 야간의 구문을 더했다.
    • HTML파일을 웹 브라우저에서 그대로 열어보면 HTML 주석이기 때문에 이 부분이 웹 브라우저가 렌더링하지 않는다.
    • 타임리프 렌더링을 거치면 이 부분이 정상 렌더링 된다.
    • 쉽게 이야기해서 HTML 파일을 그대로 열어보면 주석처리가 되지만, 타임리프를 렌더링한 경우에만 보이는 기능이다.

 

 

🔍 블록

  • <th:block>은 HTML 태그가 아닌 타임리프의 유일한 자체 태그다.
  • 타임리프의 속성을 사용하기 애매한 경우에 사용된다.
  • 대표적으로 th:each로 반복하고자 할 때 반복의 대상이 한 요소가 아니라 동등한 레벨의 여러 요소를 그룹화하여 반복할 때 th:block이 유용하다.

 

📌 컨트롤러

@GetMapping("/block")
public String block (Model model) {
    addUsers(model);
    return "basic/block";
}

 

📌 HTML

<!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"> </script>
  • 자바스크립트 인라인을 사용할 경우 편리해진 부분은 다음과 같다.
    • 문자열에는 자동으로 따옴표를 붙여준다.
    • 객체는 자동으로 JSON 형식으로 만들어준다.
      • 인라인 사용 전은 객체의 toString()이 호출된다.
      • 인라인 사용 후는 객체를 JSON으로 변환해준다.
    • 자바스크립트에서 문제가 될 수 있는 문자가 있으면 이스케이프 처리도 해준다
      • 예) " → \"
    • HTML에서 바로 여는 경우와 타임리프에서 렌더링 하는 경우 둘 다 문제없이 값을 넣을 수 있다. 인라인 전에는 내추럴 템플릿 기능이 적용하지 않고 렌더링 내용을 주석 처리한다. 반대로 인라인 후에는 내추럴 템플릿 기능이 동작하여 주석 부분이 사라지고 내용이 적용된다.
      • 예) var username2 = /* [[${user.username}]] */ "test username";
        • 인라인 사용 전 : var username2 = /*userA*/ "test username"; 
        • 인라인 사용 후 : var username2 = "userA";
    • 자바스크립트 인라인 each
      • th:each와 유사하다. 반복에 사용된다.

 

📌 컨트롤러

@GetMapping("/javascript")
public String javascript(Model model) {
    model.addAttribute("user", new User("UserA", 10));
    addUsers(model);
    return "basic/javascript";
}

 

📌 HTML

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

 

 

🔍 템플릿 조각 

  • 공통부분을 템플릿화 하여 필요한 부분에서 해당 템플릿을 불러와 설정하는 기능
    • 예) 좌측 카테고리 영역, 상단 영역, 하단 영역 등 공통으로 상요되는 영역을 모듈화 시킨다.
  • 템플릿으로 공통 태그 만들기
    • th:fragment="name"
      • 해당 태그로 선언된 태그 내부가 템플릿이 되며 속성명이 템플릿 조각 이름이 된다.
      • 해당 템플릿 조각을 사용하고 싶은 다른 영역에서 해당 이름을 사용해 템플릿을 가져올 수 있다.
    • th:fragment="name" (param1, param2)
      • 속성명에 (param1, param2) 처럼 파라미터를 넣어서 전달할 수 있다.
      • 파라미터는 템플릿 조각 내에서 사용할 수 있다.
      • 사용법은 기존에 사용하던 attribute와 동일하다.

 

📌 컨트롤러

package hello.thymeleaf.basic;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

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

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

 

📌 HTML (footer)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<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>

 

📌 HTML (fragmentMain)

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

<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>
  • 템플릿 조각 사용하기
    • <div th:insert="~{template/fragment/footer :: copy}"></div>
      • footer 라는 파일에 있는 fragment 중 이름이 copy인 템플릿을 가져와 안에 주입한다.
    • <div th:replace="~{template/fragment/footer :: copy}"></div>
      • footer라는 파일에 있는 fragment 중 이름이 copy인 템플릿을 가져와 해당 태그와 교체한다.
      • 부분 포함 단순 표현식으로 원래는 ~{...} 를 사용해야하지만 경로가 단순하면 생략할 수 있다.
    • <div th:replace="~{template/fragment/footer :: copyParam ('데이터1', '데이터2')}"></div>
      • 해당 템플릿에 파라미터를 추가하고 싶을 때 사용한다.

 

✔ 정리

  • 공통된 부분을 하나의 템플릿으로 만들어 사용할 수 있다.
  • th:fragment="이름" 속성을 추가하면 템플릿이 되며 다른 곳에서 이름으로 사용할 수 있다.
  • th:insert, th:replace로 템플릿을 사용할 수 있다.
  • 기본적으로 조각 표현식 ~{...}을 사용해야하지만 표현이 간단하면 생략 가능
  • 파라미터는 (param, ...) 방식으로 사용 가능하다. 
    • <div th:replace="~{template/fragment/footer :: copyParam ('데이터1', '데이터2')}"></div>

 

 

🔍 템플릿 레이아웃1 - HTML head 

  • 템플릿은 코드 조각을 가지고 와서 사용할 수도 있지만 더 확장해서 코드 조각을 레이아웃에 넘겨서 사용할 수도 있다.
  • 단순히 변수만 파라미터로 넘겨주는 것이 아니라 태그 자체를 단수 혹은 복수로 넘겨줘서 템플릿을 완성시킬 수 있다.

 

📌 컨트롤러

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

 

📌 HTML (base)

<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>
  • <title th:replace="${title}">레이아웃 타이틀</title>
    • 파라미터로 전달받은 title 태그로 교체한다.
  • <th:block th:replace="${links}" />
    • 파라미터로 전달받은 links 태그로 교체한다.

 

📌 HTML (layoutMain) 

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

<body>
메인 컨텐츠
</body>
</html>
  • <head th:replace="template/layout/base :: common_header(~{::title},~{::link})">
    • {::title} : 현재 페이지의 title 태그들을 전달한다.
    • {::link} : 현재 페이지의 link 태그들을 전달한다. 
    • template/layout/base 파일의 common_header의 템플릿 조각을 가져온다.
    • 단, common_header의 title 태그는 layoutMain 파일의 title 태그로 대체하고, common_header의 link 태그는 layoutMain 파일의 link 태그로 대체한다.

 

 

🔍 템플릿 레이아웃2 - HTML 전체 수정

  • 템플릿 레이아웃은 HTML head 뿐만 아니라 html 전체를 수정할 때도 쓰인다.
  • 사용법은 그저 th:replace 속성의 위치를 html에 두면 된다.

 

 

📌 컨트롤러

@GetMapping("/layoutExtend")
public String layoutExtend() {
    return "template/layoutExtend/layoutExtendMain";
}

 

📌 HTML (layoutFile)

<!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>
  • th:replace 속성이 적용되어 있는 title 태그와 div 태그는 변경될 부분이다.

 

📌 HTML (layoutExtendMain)

<!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>
  • <html th:replace="~{template/layoutExtend/layoutFile :: layout(~{::title}, ~{::section})}" xmlns:th="http://www.thymeleaf.org">
    • th:replace 속성을 html 전체에 적용 시켰다.
    • layoutFile 파일의 layout 템플릿 조각을 가져온다.
    • layout 템플릿 조각을 가져오기 전에 title 태그와 section 태그를 파라미터로 전달한다.
    • layout 템플릿 조각은 두 파라미터가 주입되고 layoutExtendMain 파일에 적용된다.

 

 

 

 

 


👀 참고자료

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-2/dashboard

 

스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 - 인프런 | 강의

웹 애플리케이션 개발에 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. MVC 2편에서는 MVC 1편의 핵심 원리와 구조 위에 실무 웹 개발에 필요한 모든 활용 기술들을 학습할 수 있

www.inflearn.com

 

https://catsbi.oopy.io/32a9458e-f452-4733-b87c-caba75f98e2d

 

1. 타임리프 - 기본 기능

목차

catsbi.oopy.io

 

728x90

'[ Spring ] > SpringMVC 2편' 카테고리의 다른 글

[Spring] 로그인 처리1 - 쿠키, 세션  (0) 2022.03.12
[Spring] 검증2 - Bean Validation  (0) 2022.03.11
[Spring] 검증1 - Validation  (0) 2022.03.07
[Spring] 메시지, 국제화  (0) 2022.03.06
[Spring] 타임리프 - 스프링 통합과 폼  (0) 2022.03.05
    '[ Spring ]/SpringMVC 2편' 카테고리의 다른 글
    • [Spring] 검증2 - Bean Validation
    • [Spring] 검증1 - Validation
    • [Spring] 메시지, 국제화
    • [Spring] 타임리프 - 스프링 통합과 폼
    쿠릉쿠릉 쾅쾅
    쿠릉쿠릉 쾅쾅
    깃허브 주소 : https://github.com/kureung

    티스토리툴바