minlog
article thumbnail
Published 2023. 3. 25. 16:39
[ Spring Boot ] Thymeleaf BackEnd/Spring Boot

1.  

2. Thymeleaf

 

순수 html 파일을 웹 브라우저에서 열어 내용 확인이 가능하다. 

뷰 템플릿을 거치면 동적으로 변경된 결과를 확인 할 수 있다.

순수한 html을 유지하면서 동적 템플도 사용할 수 있는 타임리프의 특징을 네츄럴 템플릿이라고한다.

 

 

 

2.1. 💡템플릿 설정

 

📑 build.gradle

<code />
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

스프링 부트가 자동으로 ThymeleafViewResolver 와 필요한 스프링 빈들을 등록한다. 그리고 다음 설정도 사용한다. 이 설정은 기본 값 이기 때문에 변경이 필요할 때만 설정하면 된다.

 

 

📑 application.properties

<code />
spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html

자동으로 설정된다. 

 

 

 

2.2. 💡뷰 템플릿 경로

src/main/resources/templates

 

 

 

2.3. 💡뷰 템플릿 마크업 

 

2.3.1. - thymeleaf 사용 선언

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

 

 

2.3.2. - th:text 변경

${data} 가 있을 경우 텍스트로 들어가게된다.

<java />
<p th:text="${data}">empty</p>

 

 

 

2.3.3. - th:href 속성 변경

URL 링크 표현식 @{...}

 

프로퍼티  >   th:href="@{/basic/items/{itemId} (itemId=${item.id}) }"

쿼리파라미터 > th:href="@{/basic/items/{itemId} (itemId=${item.id} , query='text') }"

ex _생성링크 : http:localhost:8080/basic/items/1?query=text

<java />
<td><a href="item.html" th:href="@{/basic/items/{itemId}(itemId=${item.id})}" th:text="${item.id}">회원아이디</a></td>

 

 

2.3.4. - th:onClick 속성 변경

리터럴 대채 문법 | ... |

th:onclick="|location.href='@{/basic/items/add}'|" 

<java />
<button class="btn btn-primary float-end" th:onclick="|location.href='@{/basic/items/add}'|" onclick="location.href='addForm.html'" type="button">상품 등록</button>

 

 

2.3.5. -  th:each 반복출력

모델에 포함된 ${items} 컬렉션 데이터가 item 변수에 하나씩 넣어주고  반복문 안에서 item 변수를 사용 가능하다.

 

변수식 표현식 ${..}

  • 모델에 포함된 값이나, 타임리프 변수 선언한 값을 조회가능
  • 프로퍼티 접근법을 사용한다.  : item.getPrice()
<code />
<tr th:each="item : ${items}"> <td><a href="item.html" th:href="@{/basic/items/{itemId}(itemId=${item.id})}" th:text="${item.id}">회원아이디</a></td> <td><a href="item.html" th:href="@{/basic/items/{itemId}(itemId=${item.id})}" th:text="${item.itemName}">상품명</a></td> <td th:text="${item.price}">상품 가격</td> <td th:text="${item.quantity}">상품 수량</td> </tr>

 

profile

minlog

@jimin-log

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!