기타

Thymeleaf 문법 정리

YB CHA 2023. 10. 26.

 

 

타임리프(Thymeleaf) ?

타임리프는 HTML, CSS, JavaScript 일반 텍스트를 처리할 수 있는 웹 및 독립형 환경에서 사용할 수 있는 Java 템플릿 엔진입니다. 서버에서 클라이언트에게 응답할 브라우저 화면을 만들어주는 역할을 합니다.

 

 

타임리프 장점

JSP와 달리 프로토타입 코드를 작성할 수 있습니다. JSP는 기존의 html 코드와 동시에 코드를 작성할 수 없어 프로토타입 코드를 작성할 수 없습니다. 타임리프는 코드를 변경하지 않기 때문에 프론트, 백엔드 간의 협업이 편해집니다.

 

 

타임리프 설정법

build.gradle 

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
}

 

HTML

<html xmlns:th="http://www.thymeleaf.org" th:lang="ko">

 

 

타임리프 문법

 

xnlns:th

  • 타임리프의 th속성을 사용하기 위해 선언된 네임스테이스입니다.
  • 순수 HTML로만 이루어진 페이지 경우 선언하지 않아도 됩니다.
<html xmlns:th="http://www.thymeleaf.org" th:lang="ko">

 

th:text

  • JSP의 EL표현식인 ${}처럼 타임리프도 ${} 표현식을 사용해 컨트롤러에서 전달받은 데이터에 접근할 수 있습니다.
<div th:text="${post.title}"></div>

 

th:href

  • <a>태그의 href 속성과 동일하며 괄호안에 url주소를 입력하면 됩니다.
<a th:href="@{/yuvyn/tistory/{postId}(postId=${post.boardId})}"></a>

 

th:with

  • 변수형태의 값을 재정의 하는 속성으로 새로운 변수값을 생성할 수 있습니다.
<div th:with="message='yuvyn tistory'">
        <p th:text="${message}"></p>
    </div>

 

th:value

  • input의 value에 값을 삽입할 때 사용합니다.
  • 여러개의 값을 넣을때는 + 기호를 사용합니다.
<input type="text" id="name" th:value="*{name}" />

 

th:block

  • 타임리프 표현을 어느 곳에서든 사용할 수 있도록 하는 구문입니다.
  • 해당기능은 동적인 처리가 필요 할 때 사용되며 주로 layout기능이나 switch에 사용이 많이 됩니다.
<div th:block="header" th:remove="tag">

 

th:fragment

  • 웹페이지에 메뉴, 네비바와 같이 반복되는 영역들에 사용하여 코드를 정리해주어 재사용성을 높입니다.
<div th:fragment="content">
               <p>내용입니다.</p>
    </div>

 

th:replace

  • JSP의 <include>태그와 유사 속성입니다.
  • fragment로 조각화한 공통 영역을 HTML에 삽입하는 역할을 합니다.
<header th:replace="fragments/header"></header>

 

th:insert

  • insert는 태그 내로 조각을 삽입하는 방법입니다. 형식은 replace와 동일합니다.
 <div th:insert="fragments/header"></div>

 

th:action

  • <form>태그 사용시, 해당 경로로 요청을 보낼 때 사용합니다.
<form th:action="@{/submit}" method="post">
	<input type="text" id="username" name="username" />
</form>

 

th:object

  • <form>태그에서 테이터를 보내기 위해 submit을 할 때 데이터가 th:object 속성을 통해 지정한 객체에 값을 담아 넘깁니다. 이때 값을 th:field 속성과 함께 사용하여 넘깁니다.
  • controller와 view사이 DTO클래스 객체라고 생각하시면 됩니다.
public class User {
    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}
<form th:object="${user}" method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" th:field="*{username}" />
        <button type="submit">Submit</button>
    </form>

 

th:field

  • th:object 속성과 함께 thLfield를 이용해 HTML 태그에 멤버 변수를 매핑할 수 있습니다.
  • th:object와 th:field는 Controller에서 특정 클래스의 객체를 전달 받은 경우에만 사용 가능합니다.
public class User {
    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}
<form th:object="${user}" method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" th:field="*{username}" />
        <button type="submit">Submit</button>
    </form>

 

th:if, th:unless

  • Java의 조건문에 해당하는 속성입니다. 각각 if와 else를 뜻합니다.
  • th:unless는 일반적인 언어의 else 문과는 달리 th:if에 들어가는 조건과 동일한 조건을 지정해야 한다.
<div th:if="${loggedIn}">
        <p>안녕하세요, <span th:text="${username}"></span>!</p>
    </div>
    <div th:unless="${loggedIn}">
        <p>로그인을 해주세요.</p>
    </div>

 

th:each

  • JSP의 JSTL에서 <c:foreach> 그리고 JAVA의 반복문 중 for문을 뜻합니다.
  • ${list}로 값을 받아온 것을 변수로 하나씩 가져온다는 뜻으로, 변수는 이름을 마음대로 지정할 수 있습니다.
<li th:each="item : ${items}">
	<span th:text="${item}"></span>
</li>

 

th:Lswitch, th:case

  • JAVA의 switch-case문과 동일합니다.
  • switch case문으로 제어할 태그를 th:block으로 설정하고 그 안에 코드를 작성합니다.
<div th:switch="${userRole}">
	<p th:case="'user'">안녕하세요 !</p>
</div>

 

 

이상으로 Thymleaf 문법에대해 알아봤습니다.

'기타' 카테고리의 다른 글

[빌드 도구] Gradle VS Maven 차이점  (0) 2023.10.26

댓글