[Thymeleaf] 기본 문법

2023. 10. 17. 15:48·Web & Android/Thymeleaf

th:text

화면에 데이터 출력

textarea에 넘겨받은 변수값을 표시할 때 사용한다.

th:value로 하면 안뜬다.

  • 예제1

      <body>
      <h1>Hello World!!!</h1>
      <p th:text="${data}">스프링 부트 수업 중</p>
      </body>
    @Controller
    public class ThymeleafController {
    
        @GetMapping("/thymeleaf/ex1")
        public String ex1(Model model) {
    
            model.addAttribute("data", "SpringBoot Study");
    
            return "thymeleaf/ex1";
        }
    
    }
    
    // 출력 결과
    // SpringBoot Study
  • 예제2

    <body>
    <h1>Hello World!!!</h1>
    <p th:text="${data.x}">스프링 부트 수업 중</p>
    </body>
    @Controller
    public class ThymeleafController {
    
        @GetMapping("/thymeleaf/ex1")
        public String ex1(Model model) {
            Point p = new Point(10, 20);
    
            model.addAttribute("data", p);
    
            return "thymeleaf/ex1";
        }
    
    }
    
    // 출력 결과
    // 10.0

1. 상품 데이터 출력용 DTO 클래스

  • 상품 클래스 자체를 반환하지 않고 DTO 객체 이용
package kr.spring.item.dto;
// 아이템 Dto
import kr.spring.utils.entity.BaseEntity;
import lombok.Getter;
import lombok.Setter;

import java.time.LocalDateTime;

@Getter // 반드시 붙여야 함
@Setter // 필수는 아님
public class ItemDto extends BaseEntity {

    private Long id;                     // 상품 코드

    private String itemNm;               // 상품 이름

    private int price;                   // 상품 가격

    private int stockNumber;             // 재고 수량

    private String itemSellStatus;

    private String itemDetail;           // 상품 상세 설명

    private LocalDateTime regTime;       // 등록 시간

    private LocalDateTime updateTime;    // 수정 시간

}

2. 상품 DTO 출력 Controller

package kr.spring.thymeleaf.controller;

import kr.spring.item.dto.ItemDto;
import lombok.extern.java.Log;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.awt.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Controller
@Log4j2 // 로그 사용
@RequestMapping("/thymeleaf")
public class ThymeleafController {

    @GetMapping("/ex1")
    public String ex1(Model model) {
        Point p = new Point(10, 20);

        model.addAttribute("data", p);

        return "thymeleaf/ex1";
    }

    //    값 전달 연습
    @GetMapping("/ex2")
    public String ex2(Model model) {

        ItemDto itemDto = new ItemDto();
        itemDto.setItemDetail("상품 상세 설명");
        itemDto.setItemNm("테스트 상품 1");
        itemDto.setPrice(10000);
        itemDto.setRegTime(LocalDateTime.now());

        model.addAttribute("itemDto", itemDto);

        return "thymeleaf/ex2";
    }
]

3. 상품 DTO 출력 Thymeleaf

  <!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <h1>상품 정보</h1>
  <div>
      상품명 : <span th:text="${itemDto.itemNm}"></span>
  </div>
  <div>
      상품설명 : <span th:text="${itemDto.itemDetail}"></span>
  </div>
  <div>
      상품가격 : <span th:text="${itemDto.price}"></span>
  </div>
  <div>
      상품등록일 : <span th:text="${itemDto.regTime}"></span>
  </div>

</body>
</html>

4. 출력 결과


th:each

반복문

1. 상품 DTO 출력 Cotroller

@GetMapping({"/ex3", "/ex4"})
    public void ex3(Model model) {

        List<ItemDto> list = new ArrayList<>();

        for(int i=1; i<=10; i++) {
            ItemDto itemDto = new ItemDto();
            itemDto.setItemDetail("상품 상세 설명" + i);
            itemDto.setItemNm("테스트 상품" + i);
            itemDto.setPrice(10000 * i);
            itemDto.setRegTime(LocalDateTime.now());

            list.add(itemDto);
        }

        model.addAttribute("list", list);

    }

2. 상품 DTO 출력 Thymeleaf

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <h1>상품 정보 리스트</h1>
  <table border="1">
      <thead>
        <tr>
            <td>번호</td>
            <td>상품명</td>
            <td>상품설명</td>
            <td>가격</td>
            <td>상품등록일</td>
        </tr>
      </thead>
      <tbody>
        <tr th:each="itemDto, status : ${list}"> <!-- status : 자동 증가 숫자 -->
            <td th:text="${status.index}"></td>
            <td th:text="${itemDto.itemNm}"></td>
            <td th:text="${itemDto.itemDetail}"></td>
            <td th:text="${itemDto.price}"></td>
            <td th:text="${itemDto.regTime}"></td>
        </tr>
      </tbody>
      <tfoot></tfoot>
  </table>

</body>
</html>

3. 출력 결과


th:if, th:unless

타임리프에서 조건문 처리

ex) 순번이 짝수이면 ‘짝수’를 출력하고, 짝수가 아니라면 ‘홀수’를 출력

1. 상품 DTO 출력 Controller

  • 위와 동일
@GetMapping({"/ex3", "/ex4"})
    public void ex3(Model model) {

        List<ItemDto> list = new ArrayList<>();

        for(int i=1; i<=10; i++) {
            ItemDto itemDto = new ItemDto();
            itemDto.setItemDetail("상품 상세 설명" + i);
            itemDto.setItemNm("테스트 상품" + i);
            itemDto.setPrice(10000 * i);
            itemDto.setRegTime(LocalDateTime.now());

            list.add(itemDto);
        }

        model.addAttribute("list", list);

    }

2. 상품 DTO 출력 Thymeleaf

  • 위와 동일 (순번 처리 부분만 변경)
  <!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">
      <thead>
        <tr>
            <td>번호</td>
            <td>상품명</td>
            <td>상품설명</td>
            <td>가격</td>
            <td>상품등록일</td>
        </tr>
      </thead>
      <tbody>
        <tr th:each="itemDto, status : ${list}"> <!-- status : 자동 증가 숫자 -->
            <td th:if="${status.even}" th:text="짝수" style="color: red"></td>
            <td th:unless="${status.even}" th:text="홀수" style="color: blue"></td>
            <td th:text="${status.index}"></td>
            <td th:text="${itemDto.itemNm}"></td>
            <td th:text="${itemDto.itemDetail}"></td>
            <td th:text="${itemDto.price}"></td>
            <td th:text="${itemDto.regTime}"></td>
        </tr>
      </tbody>
      <tfoot></tfoot>
  </table>

</body>
</html>

3. 출력 결과


th:switch, th:case

타임리프에서 조건문 처리

여러 개의 조건을 처리할 때 사용


th:href

@{ } 안에 URL 지정

thymeleaf에서 링크를 처리하는 문법


th:replace

기존 내용 완전히 대체

th:replace="파일경로 :: fragment이름이나 선택자"

:: 뒤에 생략하면 해당 파일의 전체 내용을 가져온다.


th:insert

기존 내용의 바깥쪽 태그는 그대로 유지하면서 추가


th:fragment

fragment 정의

header, footer, 부트스트랩, 외부 라이브러리 등 공통으로 쓰이는 부분을 관리하기 쉬워짐

  • implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect’ 의존성 추가

th:value

input에 넘겨 받은 변수 값을 표시할 때 사용한다.

저작자표시 비영리 변경금지 (새창열림)

'Web & Android > Thymeleaf' 카테고리의 다른 글

[Thymeleaf] 날짜 변환  (1) 2023.10.17
[Thymeleaf] 페이지 레이아웃  (1) 2023.10.17
[Thymeleaf] Thymeleaf  (0) 2023.10.17
'Web & Android/Thymeleaf' 카테고리의 다른 글
  • [Thymeleaf] 날짜 변환
  • [Thymeleaf] 페이지 레이아웃
  • [Thymeleaf] Thymeleaf
woojin._.
woojin._.
여러가지 개발을 해보며 발생하는 이야기들에 대한 블로그입니다:)
  • woojin._.
    Jin's Dev Story
    woojin._.
  • 전체
    오늘
    어제
    • 분류 전체보기 (829)
      • Tools (25)
        • eGovFrame (3)
        • GeoServer (3)
        • QGIS (2)
        • LabelImg (2)
        • Git (6)
        • GitHub (1)
        • Eclipse (7)
        • Visual Studio (1)
      • Web & Android (121)
        • SpringBoot (37)
        • Three.js (2)
        • Spring Data JPA (9)
        • 스프링 부트 쇼핑몰 프로젝트 with JPA (25)
        • Thymeleaf (4)
        • Spring Security (15)
        • Flutter (29)
      • Programming Language (61)
        • JAVA (27)
        • JavaScript (14)
        • Dart (2)
        • Python (15)
        • PHP (3)
      • Database (43)
        • PostgreSQL (32)
        • MYSQL (7)
        • Oracle (3)
        • MSSQL (1)
      • SERVER (17)
        • TCP_IP (3)
        • 리눅스 (7)
        • AWS (7)
      • Coding Test (445)
        • 백준[JAVA] (108)
        • 프로그래머스[JAVA] (260)
        • 알고리즘 고득점 Kit[JAVA] (3)
        • SQL 고득점 Kit[ORACLE] (74)
      • CS 지식 (49)
        • [자료구조] (14)
        • [네트워크] (12)
        • [데이터베이스] (10)
        • [알고리즘] (9)
        • [운영체제] (4)
      • 기타 (6)
      • 자격증 & 공부 (62)
        • 정보처리기사 (2)
        • SQLD (6)
        • 네트워크관리사 2급 (5)
        • 리눅스마스터 1급 (44)
        • 리눅스마스터 2급 (1)
        • ISTQB (3)
        • 시스템보안 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 인기 글

  • 태그

    스프링
    리눅스마스터 1급
    Oracle
    플러터
    스프링부트
    프로그래머스
    programmers
    baekjoon
    스프링 부트 쇼핑몰 프로젝트 with JPA
    데이터
    Linux
    springboot
    백준
    Java
    리눅스
    CS지식
    CS
    리눅스마스터
    postgresql
    DB
    데이터베이스
    Spring Security
    Flutter
    spring
    python
    pcce 기출문제
    JPA
    자바
    시큐리티
    backjoon
  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
woojin._.
[Thymeleaf] 기본 문법
상단으로

티스토리툴바