타임리프 기본 기능

2023. 11. 8. 11:29타임리프

th:with 변수화 가능

<div th:with="first=${users[0]}">
 <p>처음 사람의 이름은 <span th:text="${first.username}"></span></p>
</div>

 

 

th:href 처리

1.@{/hello(param1=${param1}, param2=${param2})} -> /hello?param1=param1&param2=param2
2.@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})} -> /hello/param1/param2
3.@{/hello/{param1}(param1=${param1}, param2=${param2})} -> /hello/param1?param2=param2

 

layout 처리

 

head.html
-------
<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>

footer.html
------
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<footer th:fragment="copyParam (param1, param2)">
    <p>파라미터 자리 입니다.</p>
    <p th:text="${param1}"></p>
    <p th:text="${param2}"></p>
</footer>
</body>
</html>

위 베이스 layout을 작성 후

layoutMain.html
-------
<!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>
메인 컨텐츠
<footer th:replace="~{template/fragment/footer :: copyParam ('1', '2')}"></footer>
</body>
</html>

메인에서 사용하는 곳에서 replace로 해당 값을 넘겨주고 저 레이아웃을 사용할 수 있게 한다.

 

th:object -> 폼에 모델로 받은 객체를 받아서 th:field, th:errors, th:errorclass등을 사용할 수 있게 만들어줌

<form action="item.html" th:action th:object="${item}" method="post">
 <div>
 <label for="itemName">상품명</label>
 <input type="text" id="itemName" th:field="*{itemName}" class="formcontrol"
placeholder="이름을 입력하세요">
 </div>
 <div>
 <label for="price">가격</label>
 <input type="text" id="price" th:field="*{price}" class="form-control"
placeholder="가격을 입력하세요">
 </div>
 <div>
 <label for="quantity">수량</label>
 <input type="text" id="quantity" th:field="*{quantity}" class="formcontrol"
placeholder="수량을 입력하세요">
 </div>

기존에는 id=${item.itemName} value=${item.itemName}처럼 사용했다면 위 코드와 같이 간단히 사용 가능

th:field 사용시 자동으로 id name value를 받아온 값으로 바인딩해줌

이 기능을 사용 시 체크박스나 라디오 같은 경우 value값이 일치하면 자동으로 체크처리

th:for=${#ids.prev("itemName")} 이것은 th:field가 루프를 돌면서 만들때 id 값을 itemName1, itemName2 이런식으로 맞춰주는데 for값과 id값을 맞춰주기 위해 사용