Learn & Record
Spring Boot (Thymleaf, th:with를 이용한 변수, 반복문과 제어문 처리, 반복문의 status 변수, th:if / th:unless / th:switch, 인라인 처리, Thymeleaf의 레이아웃 기능 ) 본문
Spring Boot (Thymleaf, th:with를 이용한 변수, 반복문과 제어문 처리, 반복문의 status 변수, th:if / th:unless / th:switch, 인라인 처리, Thymeleaf의 레이아웃 기능 )
Walker_ 2024. 5. 8. 11:001. Thymleaf
- 부트에서는 뷰를 jsp보다는 템플릿이라는 것에 기능을 맡김.
- jsp는 뷰만 담당하기에는 기능이 너무 많음
- 단순한 기능만 가진 템플릿을 만들어서 뷰를 담당하게 함
- 기능이 단순해서 템플릿을 퍼브리셔가 담당해도 됨
- 1) 컨트롤러에 데이터를 받아서 html에 출력하는 기능
- 2) 출력을 하려면 반복문(예 : 게시판 목록)과 조건문(예 : 페이징) 기능이 필요
- Thymeleaf가 작성하는 부분의 에러를 찾기 위해 주석 처리를 해야할 때는
- '<!--/*---*/-->'를 이용하는 것이 좋음 (페이지 소스 보기에서 안 보임)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!-- inlining 사용 -->
<h4>[[${list}]]</h4>
<hr>
<!-- 'th:' 속성 사용 -->
<!-- <h4 th:text="${list}"></h4>-->
<!--/* 주석 */-->
</body>
</html>
2. th:with를 이용한 변수
- 임시로 변수를 선언해야 하는 상황에서는 'th:with'를 이용해서 간단히 처리 가능.
- '변수명 = 값'의 형태로 ','를 이용해서 여러 개를 선언할 수도 있음
<div th:with="num1 = ${10}, num2 = ${20}">
<h4 th:text="${num1 + num2}"></h4>
</div>
3. 반복문과 제어문 처리
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!-- inlining 사용 -->
<!-- <h4>[[${list}]]</h4>-->
<!-- <hr>-->
<!-- 'th:' 속성 사용 -->
<!-- <h4 th:text="${list}"></h4>-->
<!--/* 주석 */-->
<ul>
<li th:each="str: ${list}" th:text="${str}"></li>
</ul>
<ul>
<th:block th:each="str: ${list}">
<li>[[${str}]]</li>
</th:block>
</ul>
</body>
</html>
4. 반복문의 status 변수
<ul>
<li th:each="str, status: ${list}">
[[${status.index}]] -- [[${str}]]
</li>
</ul>
- ex1.html 위 코드 작성
5. th:if / th:unless / th:switch
<ul>
<li th:each="str, status: ${list}">
<span th:if="${status.odd}">ODD -- [[${str}]]</span>
<span th:unless="${status.odd}">EVEN -- [[${str}]]</span>
</li>
</ul>
<ul>
<li th:each="str, status: ${list}">
<span th:text="${status.odd} ? 'ODD ---' + ${str}"></span>
</li>
</ul>
<ul>
<li th:each="str, status: ${list}">
<span th:text="${status.odd} ? 'ODD --- '+${str} : 'EVEN ---'+${str}"></span>
</li>
</ul>
<!-- switch문-->
<ul>
<li th:each="str, status: ${list}">
<th:block th:switch="${status.index % 3}">
<span th:case="0">0</span>
<span th:case="1">1</span>
<span th:case="2">2</span>
</th:block>
</li>
</ul>
- ex1.html 위 코드 작성
6. 인라인 처리
class SampleDTO {
private String p1, p2, p3;
public String getP1() {
return p1;
}
public String getP2() {
return p2;
}
public String getP3() {
return p3;
}
}
@GetMapping("/ex/ex2")
public void ex2(Model model) {
log.info("ex/ex2................");
List<String> strList = IntStream.range(1,10)
.mapToObj(i -> "Data"+i)
.collect(Collectors.toList());
model.addAttribute("list", strList);
Map<String, String> map = new HashMap<>();
map.put("A", "AAAA");
map.put("B", "BBBB");
model.addAttribute("map", map);
SampleDTO sampleDTO = new SampleDTO();
sampleDTO.p1 = "Value -- p1";
sampleDTO.p2 = "Value -- p2";
sampleDTO.p3 = "Value -- p3";
model.addAttribute("dto", sampleDTO);
}
- SampleController에 내부 클래스로 SampleDTO와 ex2 Model 생성
<!DOCTYPE html>
<html xmlns:th="http://www.thymleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${list}"></div>
<div th:text="${map}"></div>
<div th:text="${dto}"></div>
<script th:inline="javascript">
const list = [[${list}]]
const map = [[${map}]]
const dto = [[${dto}]]
console.log(list)
console.log(map)
console.log(dto)
</script>
</body>
</html>
- ex2.html 파일 생성 후 위 코드 작성
- 출력 확인
7. Thymeleaf의 레이아웃 기능
// 레이아웃 기능
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:3.1.0'
- 기능 사용을 위해 위 코드 build.gradle에 추가
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<h3>Sample Layout Header</h3>
</div>
<div layout:fragment="content">
<p>Page content goes here</p>
</div>
<div>
<h3>Sample Layout Footer</h3>
</div>
<th:block layout:fragment="script">
</th:block>
</body>
</html>
- templates에 layout 폴더 생성 후 > layout1.html 파일 생성 후 위 코드 작성
@GetMapping("/ex/ex3")
public void ex3(Model model) {
model.addAttribute("arr", new String[] {"AAA", "BBB", "CCC"});
}
- SampleController에 위 코드 추가
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layout/layout1.html}">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div layout:fragment="content">
<h1>ex3.html</h1>
</div>
</body>
</html>
- ex3.html 파일 생성후 > 위 코드 작성
- 출력 확인
<script layout:fragment="script" th:inline="javascript">
const arr = [[${arr}]]
</script>
- ex3에 스크립트 코드 추가
공부 과정을 정리한 것이라 내용이 부족할 수 있습니다.
부족한 내용은 추가 자료들로 보충해주시면 좋을 것 같습니다.
읽어주셔서 감사합니다 :)