Back-end/Spring Boot

[Spring Boot] Thymeleaf

Bay Im 2023. 11. 3. 14:02
  • Thymeleaf 이란?
    • 템플릿 엔진의 일종이며 html 태그에 속성을 추가하여 페이지에 동적으로 값을 추가하거나 처리
      • 템플릿 엔진
        • 템플릿 양식과 데이터가 합쳐져 html 문서를 출력하는 소프트웨어
        • 서버에서 DB나 API 등을 통해 가져온 데이터를 템플릿에 넣어서 클라이언트에 전달
        • 고정인 부분은 템플릿, 동적으로 생성되는 부분을 타임리프로 템플릿 특정 위치에 끼워넣는 것
    • html 페이지 개발자 도구로 열어도 th: 속성은 표시되지 않는다.
<!-- 예제 -->
<input type="text"
value="text"
th:value="${item}">

-> input 태그: th:value의 값이 존재하면 해당 값 세팅, 존재하지 않으면 value=의 값 세팅

 

  • Thymeleaf 사용
    1. ThymeleafViewResolver 등록해야 사용 가능
      • Gradle
        • build.gradle
        implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
        
      • Maven
        • pom.xml
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        
    2. Thymeleaf를 사용할 html 파일에 태그 수정

 

  • Thymeleaf 문법
    • 대부분 html 속성을 th:ㅁㅁㅁ 형태로 변경 (ex. th:text=”${변수명}”)
    • ${…}
      • 변수
    • @{…}
      • URL 링크 표현식
      • 클래스 가져올 때 th:object="${board}"
    • *{…}
      • 선택 변수
      • th:object에서 선택한 객체에 접근
    • #{…}
      • 메시지
      • properties 같은 외부 자원에서 코드에 해당하는 문자열을 가져온다.
    • |…|
      • 리터럴 대체
    • th:each
      • 반복문
      • th:each="board : ${boardList}"
    • th:if
      • 조건문
      • th:if="${iterState.count} % 2 != 0"
728x90