달리는 두딘

[Spring] Thymeleaf 기본 문법 본문

지식노트

[Spring] Thymeleaf 기본 문법

디두딘 2022. 4. 28. 11:03

1. Thymeleaf 기본 표현식 - {}, ${}, ...

  • 변수 : ${...} - ${student.id}
  • 선택자 : {...} - {id}
  • 메시지 : #{...} - #{id}
  • 링크URL : @{...} - @{<https://www.naver.com>}
  • 부분적 표현 : ~{...} -
  • 조건 연산자 : and, or, not, !
    • ${student.age} > 20 and ${student.age} < 10 처럼 각각 분리하여서 사용하거나
    • ${student.age > 20 or student.age < 10} 처럼 한 번에 묶어서 사용하는 것도 가능
  • 텍스트 결합 : ${student.id}+${student.name}
  • 문장 결합 : |학생 아이디 : ${student.id}, 학생 이름 : ${student.name} | - | 로 전체 문장을 묶어줌
  • if-then : if ? then - ${student.age < 20} ? '청소년'
  • if-then-else : if ? then : else - ${student.age < 20} ? '청소년' : '성인'
  • default : value ?: defaultValue

2. Thymeleaf 기본 문법 - 데이터 바인딩, 조건문

1) 데이터 바인딩 - th:text, th:value, th:placeholder

p, span, div 등의 태그에서 데이터를 텍스트로 바인딩할 때 사용한다.

th:utext 라는 속성도 있는데, utext의 경우 html 태그를 escape처리 하지 않기 때문에 보안에 취약해서 사용할 때 주의해야 한다.

@RequestMapping("selectStudentInfo")
ModelAndView selectStudentInfo() {
    ModelAndView mav = new ModelAndView("/selectStudentInfo");
        
    Student student = new Student();
    student.setId("210000001");
    student.setName("Anne Marie");
    student.setAge(29);
        
    /** thymeleaf에서 사용할 object명, object를 ModelAndview에 넣어준다. */
    mav.addObject("student", student);
        
    return mav;
}
<p th:text="${student.id}"></p>		<!-- 210000001 -->
<input type="text" th:placeholder="${student.name}" /> <!-- Anne Marie -->
<p><span th:utext="${student.age}"></span></p>  <!-- 29 -->

2) 조건문 - th:if, th:unless

조건문을 사용할 때 else 대신 unless를 사용한다. 주의할 점은 if문의 조건식과 unless의 조건식을 동일하게 해주어야 한다.

<p th:if="${student.grade > 80}">
  합격입니다!!!
</p>
<p th:unless="${student.grade > 80}">
  불합격.. 좀 더 노력하세요!
</p>

3) form - th:object

@RequestMapping("selectStudentInfo")
ModelAndView selectStudentInfo() {
    ModelAndView mav = new ModelAndView("/selectStudentInfo");
        
    Student student = new Student("210000001", "Anne Marie", 29);
     
    List<Student> studentList = new ArrayList<>();
    studentList.add(student);
    studentList.add(new Student("210000002", "Lukas Graham", 33));
    studentList.add(new Student("210000003", "Christina Grimmie", 22));
  
    /** thymeleaf에서 사용할 object명, object를 ModelAndview에 넣어준다. */
    mav.addObject("studentList", studentList);
        
    return mav;
}

3. 반복문 - th:each, 상태변수 사용(index, count 등)

리스트 객체를 반복할 때 사용한다.

@RequestMapping("selectStudentInfo")
ModelAndView selectStudentInfo() {
    ModelAndView mav = new ModelAndView("/selectStudentInfo");
        
    Student student = new Student("210000001", "Anne Marie", 29);
     
    List<Student> studentList = new ArrayList<>();
    studentList.add(student);
    studentList.add(new Student("210000002", "Lukas Graham", 33));
    studentList.add(new Student("210000003", "Christina Grimmie", 22));
  
    /** thymeleaf에서 사용할 object명, object를 ModelAndview에 넣어준다. */
    mav.addObject("studentList", studentList);
        
    return mav;
}
<table>
  <tr th:each="student : ${studentList}">
    <td th:text="|${student.id} : ${student.name}|"></td>
    <td th:text="|나이: ${student.age}|"
  </tr>
</table>

<!-- /* 출력 결과 */ -->
210000001 : Anne Marie
나이: 29
210000002 : Lukas Graham
나이: 33
210000003 : Christina Grimmie
나이: 22

th:each를 사용할 때 기본적으로 status 변수를 제공해주고 이를 이용하여 index나 count 등의 값을 사용할 수 있다. 기본적으로 변수명Stat 로 사용할 수 있으며, 변수명을 다르게 사용하고 싶을 경우 직접 명시할 수 있다. index의 경우 0부터 시작한다.

<aside> 💡 index : 현재 인덱스(0부터 시작) count : 현재 인덱스(1부터 시작) size : 전체 개수 current : 현재 요소 even : 현재 반복이 짝수인지(boolean) odd : 현재 반복이 홀수인지(boolean) first : 현재 반복이 첫번째인지(boolean) last : 현재 반복이 마지막인지(boolean)

</aside>

<!-- /* 상태변수명을 바꾸고 싶을 경우 직접 명시할 수 있다.
			<tr th:each="student, stat : ${studentList}"> */ -->
<div th:each="student : ${studentList}">
  <p th:text="${'index: ' + studentStat.index}"></p>
  <p th:text="${'count: ' + studentStat.count}"></p>
  <p th:text="${'size: ' + studentStat.size}"></p>    
  <p th:text="${'current: ' + studentStat.current}"></p>
  <p th:text="${'even: ' + studentStat.even}"></p>
  <p th:text="${'odd: ' + studentStat.odd}"></p>
  <p th:text="${'first: ' + studentStat.first}"></p>
  <p th:text="${'last: ' + studentStat.last}"></p>
</div>

4. 기타 문법, 타임리프 주석 사용법

1) th:block

th:if문을 사용하고 싶은데, html 태그는 사용하고 싶지 않거나 사용할 수 없는 경우라면? th:block을 사용하여 타임리프 문법을 사용할 수 있습니다.

<th:block th:if="${student.grade < 60}" th:text="|${student.name} 불합격!|"></th:block>
<th:block th:if="${student.grade >= 60 and student.grade < 90}" th:text="|${student.name} 통과! B등급!!|"></th:block>
<th:block th:if="${student.grade >= 90}" th:text="|${student.name} 통과! A등급!!|"></th:block>

xmlns:th

  • 타임리프의 th속성을 사용하기 위해 선언된 네임스페이스이다.
  • 순수 HTML로만 이루어진 페이지의 경우, 선언하지 않아도 무관하다.

th:text

  • JSP의 EL 표현식인 ${}와 마찬가지로 타임리프도 ${} 표현식을 사용해서 컨트롤러에서 전달받은 데이터에 접근할 수 있다.
  • 해당 속성은 일반적인 텍스트 형식으로 화면에 출력한다.

th:fragment

  • <head>태그에 해당 속성을 사용해서 fragment의 이름을 지정한다.
  • fragment는 다른 HTML에서 include 또는 replace 속성을 사용해서 적용할 수 있다.

th:block

  • layoutL:fragment 속성에 이름을 지정해서 실제 Content 페이지의 내용을 채우는 기능이다.
  • 해당 기능은 동적(Dynamic)인 처리가 필요할 때 사용된다.

th:replace

  • JSP의 <include> 태그와 유사한 속성이다.
  • th:fragment을 통해 설정한 이름을 찾아 해당 코드로 치환한다.

th:href

  • <a> 태그의 href 속성과 동일하다.
  • 웹 애플리케이션을 구분하는 콘텍스트 경로(Context Path)를 포함한다.

xmlns:layout, xmlnslayout:decorator

  • xmlns:layout은 타임리프의 레이아웃 기능을 사용하기 위한 선언이다.
  • xmlnslayout:decorator 레이아웃으로 basic.html을 사용하겠다는 의미이다.

Gradle 추가

implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'/* Thymeleaf Layout */

선언방법

위의 방식 오류

2021-11-21 17:08:00.095  WARN 22472--- [nio-8080-exec-1] n.n.u.t.decorators.DecoratorProcessor    : The layout:decorator/data-layout-decorator processor has been deprecated and will be removed in the next major version of the layout dialect.

해결

layout:decorator="board/layout/basic" 을

layout:decorate="~{board/layout/basic} 으로 변경

즉, 아래의 코드처럼 변경 해야 한다.

th:block layout:fragment

  • layout:fragment 속성에 이름을 지정해서 실제 Content 페이지의 내용을 채우게 된다.
  • 에를 들어 글쓰기 페이지는 "write page"로, 게시글 리스트 페이지는 "list page" 이런식 이다.
  • 즉, 페이지마다 타이틀을 다르게 처리하고 싶을 때 해당 속성을 이용해서 타이틀을 동적(Dynamic)으로 처리할 수 있다.

th:action

  • <form>태그 사용시 해당 경로로 요청을 보낼때 사용한다.

th:object

  • <form>태그에서 submit을 할 때, 데이터가 th:object에 설정해둔 객체로 받아진다.
  • 즉, 컨트롤러와 뷰(화면) 사이의 DTO클래스의 객체이다.
<form class="form-horizontal" th:action="@{/board/register.do}" th:object="${board}" method="post">

th:field

  • 위의 th:object 속성을 이용하면, th:field를 이용해서 HTML 태그에 멤버 변수를 매핑 할 수 있다.
  • th:field을 이용한 사용자 입력 필드(input, textarea 등)는 id, name, value 속성 값이 자동으로 매핑된다.
  • 그렇기에, 각 속성을 따로 지정할 필요가 없다.
  • th:field는 ${}표현식이 아닌, *{}표현식을 사용한다.
  • th:object와 th:field는 컨트롤러에서 특정 클래스의 객체를 전달 받은 경우에만 사용 가능하다.
<input type="text" th:field="*{title}" class="form-control" placeholder="제목을 입력해 주세요." />

th:checked

  • 체크박스의 경우, th:checked 속성을 이용해서 조건이 "true"에 해당하면, checked 속성을 적용한다.

th:inline="javascript"

  • <script> 태그에 th:inline 속성을 javascript로 지정해야 자바스크립트를 사용할 수 있다.

th:if, th:unless

  • th:if는 if 문과 동일하고, th:unless는 else 문과 같다고 볼 수 있다.
  • th:unless는 일반적인 언어의 else 문과는 달리 th:if에 들어가는 조건과 동일한 조건을 지정해야 한다.

th:each

  • th:each는 JSTL의 <c:foreach>, 자바의 forEach와 유사한 기능이다.

th URI GET 파라미터 추가 방식

  • 일반적인 GET 파라미터 추가 방식
/board/view.do?idx=${idx}&page=${page}
  • 타임리프 GET 파라미터 추가 방식
/board/view.do(idx=${idx},page=${page}

<![CDATA[]]>

  • 타임리프는 '<','> '태그를 엄격하게 검사하기 때문에 자바스크립트 코드는 꼭 CDATA로 묶어줘야 한다.
  • CDATA는 특수문자를 전부 문자열로 치환할 때 사용한다.

'지식노트' 카테고리의 다른 글

[Spring] RestAPI  (0) 2022.04.29
[JAVA] Collection Frameworks  (1) 2022.04.28
[Spring] #{} / ${}의 차이  (2) 2022.04.28
[Spring] Controller - class method가 가질 수 있는 파라미터  (1) 2022.04.28
[Spring] Logback 적용 여정기  (2) 2022.04.28