순수 HTML 파일을 웹 브라우저에서 열어도 내용을 확인할 수 있고,
서버를 통해 뷰 템플릿을 거치면 동적으로 변경된 결과를 확인할 수 있다.
타임리프를 사용하여 정적 리소스를 동적인 뷰 템플릿으로 전환해보자.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link href="../css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container" style="max-width: 600px">
<div class="py-5 text-center">
<h2>상품 목록</h2> </div>
<div class="row">
<div class="col">
<button class="btn btn-primary float-end" onclick="location.href='addForm.html'" type="button">상품
등록</button> </div>
</div>
<hr class="my-4">
<div>
<table class="table">
<thead>
<tr>
<th>ID</th> <th>상품명</th> <th>가격</th> <th>수량</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="item.html">1</a></td>
<td><a href="item.html">테스트 상품1</a></td>
<td>10000</td>
<td>10</td>
</tr>
<tr>
<td><a href="item.html">2</a></td>
<td><a href="item.html">테스트 상품2</a></td> <td>20000</td>
<td>20</td>
</tr>
</tbody>
</table>
</div>
</div> <!-- /container -->
</body>
</html>
@Controller
@RequestMapping("/basic/items")
@RequiredArgsConstructor
public class basicItemController {
private final ItemRepository itemRepository;
@GetMapping
public String items(Model model){
List<Item> items = itemRepository.findAll();
model.addAttribute("items", items);
return "basic/items";
}
/**
* 테스트용 데이터 추가
*/
@PostConstruct
public void init(){
itemRepository.save(new Item("itemA", 10000, 10));
itemRepository.save(new Item("itemB", 20000, 20));
}
}
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<link href="../css/bootstrap.min.css" th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
</head>
<body>
<div class="container" style="max-width: 600px">
<div class="py-5 text-center">
<h2>상품 목록</h2> </div>
<div class="row">
<div class="col">
<button class="btn btn-primary float-end"
onclick="location.href='addForm.html'"
th:onclick="|location.href='@{/basic/items/add}'|"
type="button">상품 등록</button> </div>
</div>
<hr class="my-4">
<div>
<table class="table">
<thead>
<tr>
<th>ID</th> <th>상품명</th> <th>가격</th> <th>수량</th>
</tr>
</thead>
<tbody>
<tr th:each="item : ${items}">
<td><a href="item.html" th:href="@{/basic/items/{itemId} (itemId=${item.id})}" th:text="${item.id}">회원 id</a></td>
<td><a href="item.html" th:href="@{|/basic/items/${item.id}|}" th:text="${item.itemName}">상품명</a></td>
<td th:text="${item.price}">10000</td>
<td th:text="${item.quantity}">10</td>
</tr>
</tbody>
</table>
</div>
</div> <!-- /container -->
</body>
</html>
<html xmlns:th="http://www.thymeleaf.org">
`속성 변경 💡 타임리프 핵심
- th:xxx 가 붙은 부분은 서버사이드에서 렌더링 되고, 기존 것을 대체한다.
- th:xxx 이 없으면 기존 html의 xxx 속성이 그대로 사용된다.
- HTML을 파일로 직접 열었을 때, th:xxx 가 있어도 웹 브라우저는 th: 속성을 알지 못하므로 무시한다.
- 따라서 HTML을 파일 보기를 유지하면서 템플릿 기능도 할 수 있다.
URL 링크 표현식
th:href="@{/css/bootstrap.min.css}"
th:href="@{/basic/items/{itemId}(itemId=${item.id})}" 상품 ID를 선택하는 링크
th:href="@{/basic/items/{itemId}(itemId=${item.id}, query='test')}"
th:href="@{|/basic/items/${item.id}|}" 상품 이름을 선택하는 링크
상품 등록 폼으로 이동 속성 변경
onclick="location.href='addForm.html'"
👉 th:onclick="|location.href='@{/basic/items/add}'|"
리터럴 대체 문법
문자와 표현식을 분리 하지않고 편리하게 사용할 수 있다.
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
<span th:text="|Welcome to our application, ${user.name}!|">
모델에 포함된 컬렉션 데이터 변수를 반복하여 사용할 수 있다.
<tr th:each="item : ${items}">
변수 표현식
모델에 포함된 값이나, 타임리프 변수로 선언한 값을 조회할 수 있다.
<td th:text="${item.price}">10000</td>
내용의 값을 th:text 의 값으로 변경한다.
<td th:text="${item.price}">10000</td>
모델에 있는 item 정보를 획득하고 프로퍼티 접근법으로 출력한다. ( item.getId() )
<body>
<div class="container">
<div class="py-5 text-center">
<h2>상품 상세</h2>
</div>
<div>
<label for="itemId">상품 ID</label>
<input type="text" id="itemId" name="itemId" class="form-control" value="1" th:value="${item.id}" readonly>
</div>
...
HTML form에서 action 에 값이 없으면 현재 URL에 데이터를 전송한다.
...
<h4 class="mb-3">상품 입력</h4>
<form action="item.html"
th:action
method="post">
...
</form>
...