IT 공부/Spring Boot
Thymeleaf 기본 문법
Zinisang
2021. 7. 22. 18:06
타임리프는 컨트롤러를 사용하는 페이지들을 위해 동작하는
프론트 언어 이다.
다른 기능들을 구현한필요없이 html 내부에서
간편하게 사용이 가능하다.
타임리프 사용 선언
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
Include 기능
<th:block th:include="/header"/>
Replace 기능
//가져올 화면
<th:block th:fragment="setHead(head)">
~~~~ //이 내부의 내용을 가져와서 교체하겠다.
</th:block>
//받는 화면
<th:block th:fragment="setHead(head)"></th:block> //이 세팅을 가져올꺼다
<th:block th:replace="~{/경로/파일이름 :: setHead(~{this::head} )}"></th:block> //바꾸자
태그 생성 및 삭제
//태그 생성
<th:block th:text="${값.name}" />
//태그 삭제
<li th:remove="tag"></li>
태그에 값 세팅 및 연산
<div th:text="${값}"></div>
<span th:text="${값}-1"></span>
<span th:text="${값-1}"></span>
value 값 세팅
<input type="hidden" th:value="${값}"/>
반복문
<ul th:each="값 : ${값}">
<li th:text="${값['name']}"></li>
<li th:text="${값['event']}"></li>
</ul>
if 문
<span th:if="${값['name'] != null}">
// and/or 추가
<span th:if="${값['name'] != null and sports['name'] != ''}">
// if ~ else ~
<span th:if="${값['count'] != '1'}">
<span th:unless="${값['count'] != '1'}">
swich case 문
<td th:switch="${join.gender}">
<span th:case="'M'" th:text="Male" />
<span th:case="'F'" th:text="Female" />
</td>
이미지 태그에 src 속성
<img th:src="${값['pic']}" alt="" />
링크 url
// 기본적인 링크 삽입
<a th:href="@{/index}"/>
// 고정된 url과 변수를 함께 사용할 때
<a th:href="${'http://www.naver.com' + 값}" target="_blank">링크</a>
// 링크에 파라미터를 보낼 때
<a th:href="@{/board/qna/modify?id=} + ${값.id}">수정</a>
- @{ } 은 문자열을 그대로 url 로 쓰는 것이고
- ${ } 은 변수를 url 에 쓰는 것이다.
자바스크립트 안에서 타임리프 변수 사용
타임리프 변수에 [[ ]] 를 붙여준다.
// 변수 한 개
<a th:onclick="popUp( [[ ${값['event']} ]] );"></a>
// 변수 여러 개
<li th:onclick="detail( [[ ${값['code']} ]], [[ ${값['name']} ]] );">