Thymeleaf 문법 정리!

박경현·2023년 4월 4일
0

오늘은 실무에서 많이 쓰이는 템플릿 엔진인 Thymeleaf에 대해 정리해보려고 한다!!

새로운 컴퓨터 문법 배우는 느낌보다는 그냥 th:속성 이렇게 적으면 많은게 해결되는거 같았다!

템플릿엔진에 Data전달하는법 -> Model을 사용해 간단한 데이터들 정리해주기!

model에 담으면 우리가 적은 view에서 데이터를 불러다가 사용할 수 있다!

@GetMapping("/link")
public String link(Model model) {
	model.addAttribute("param1", "data1");
    return "basic/link";
}
항상 html파일의 <html 에 xmlns:th="http://www.thymeleaf.org" 해주기!
th:text는 차고로 escape!! 즉 th:text="<h5 d </h5 "해도 무시당한다!
th:utext로 해야 안에 문법이 가능해진다!

Thymeleaf 문법1 - 속성 추가하기!

th:attrappend를 사용하면 된다!

<input type="text" class="text" th:attrappend="" />
<input type="checkbox" class="text" th:checked="true" />

Thymeleaf 문법2 - 편의 객체들 소개

기본적인 넘어온 모델 뿐 아니라 세션 데이터나 스프링 빈을 직접 불러오기도 가능하다!

<span th:text="${param.paramData}"> </span>
<span th:text="${session.sessionData}"> </span>
<span th:text="${@helloBean.hello('Spring!')}"> </span>

Thymeleaf 문법3 - th:each로 반복문 구현하기!

th:each="user, userStat : ${users}" 이렇게 적으면 user에는 모델의 데이터객체 하나가,
userStat에는 전체사이즈, 현재 값, 인덱스, 카운트 등 다양한게 들어감!

<tr th:each="user, userStat : ${users}">
	<td th:text="${usetStat.count}"> </td>
    <td th:text="${user.username}"> </td>
</tr>

Thymeleaf 문법4 - block으로 th:each 구역 통째로 정하기!, 이건 속성이아니라 html 태그처럼 th 태그다!

th:block을 사용하게 되면 그 안에 있는 구역들을 전체 반복하고 싶을때 반복시키기가 용이하다!

th:block은 거의유일한 th태그!!

<th:block th:each="user : ${users}">
	<div>
    	<span th:text="${user.username}"> </span>
    </div>
    <div>
    하하하
  </div>
</th:block>

Thymeleaf 문법5 -> 조건식 if, unless 그리고 switch

th:if , th:unless(if랑 조건 반대!), th:switch를 사용하면 조건식 용이하다!

조건이 안맞으면 그 tag자체가 무시당한다!

switch는 조건이 맞으면 그 tag가 출력된다!

<tr th:each="user, userStat: ${users}">
	<td th:text="${user.username}" > </td>
	<td th:text="미성년자" th:if="${user.age <20}"> </td>
    <td th:text="미성년자" th:unless="${user.age >=20}" </td>
    
    <td th:switch="${user.age}">
    	<span th:case="10"> 10살</span>
        <span th:case="20"> 20살</span>
        <span th:case="*">기타 </span>
    </td>
</tr>

Thymeleaf 문법6 -> 링크는 th:href="@{}"로 표현하자!

첫번째 주소는 /hello
두번째 주소는 /hello?param1=data1¶m2=data2
세번째 주소는 /hello/data1?param2=data2

<ul>
	<li><a th:href="@{/hello}">기본 url </a></li>
    <li><a th:href="@{/hello(param=${param1}, param2=${param2} )}">query url </a></li>
    <li><a th:href="@{/hello/{param1}(param1=${param}, param2=${param2}) }">pathVariable + query url </a></li>
</ul>

Thymeleaf 문법 7 -> 문자열+ 객체는 || 안에 함께 적어버리자

<li th:text=" 'hello world' + ${data} "> </li>
<li th:text="|hello world ${data}|"> </li>

이제 Thymeleaf로 된 부분을 다른 html 파일에서 사용해 보자!

html파일의 경우 header, footer가 겹칠때가 많으므로 그런 경우에 대한 재사용성을 어떻게 할 수 있는지 알아보자!

th:fragment와 th:replace만 알고 있어도 90프로 이상은 다른 html 파일에서 동적으로 재사용 가능!

부분 포함 즉 <div th: 로 감싸져 있는 부분만 가져와보자!!

footer.html => 여기 안에 footer 태그를 가져와서 사용할것이다!

th:fragment="copy" 처럼 적으면 copy가 이 태그의 이름으로 쓰인다!
th:fragment="copyParam (param1, param2)" 이렇게 뒤에 ()에 있으면 동적으로 데이터 할당받을수있다!

<footer th:fragment="copy">
푸터자리
</footer>
<footer th:fragment="copyParam (param1, param2)">
	<p th:text="${param1}"> </p>
    <p th:text="${param12"> </p>
</footer>

footerMain.html
inset는 삽입 즉 <div 안에 <footer를 넣는거다!
replace는 교체 즉 <div 를 <footer로 완전 교체!

<div th:insert="~{template/fragment/footer :: copy}"> </div>
<div th:replace="~{template/fragment/footer :: copy}"> </div>
<div th:replace="~{template/fragment/footer :: copyParam('데이터1', '데이터2')}"> </div>

헤더를 통째로 가져오기!

base.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head th:fragment="common_header(title, links)">
    <meta charset="UTF-8">
    <title th:replace="${title}">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}"></th:block>
</head>

layoutMain.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head th:replace="template/layout/base :: common_header(~{::title},~{::link})">
    <meta charset="UTF-8">
    <title>main title</title>
    <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
    <link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}">
</head>
<body>
메인 컨텐츠
</body>
</html>
profile
SW로 문제를 해결하려는 열정만 있는 대학생

0개의 댓글