Heestory

01.Spring-MVC2)타임리프-기본기능 본문

개발(~국비)/Spring

01.Spring-MVC2)타임리프-기본기능

까만밀가루 2022. 11. 14. 20:59

타임리프 특징

  • 서버 사이드 HTML 렌더링(SSR)
    HTML을 동적으로 렌더링 하는 용도로 사용
  • 네츄럴 템플릿
    - 순수 HTML을 최대한 유지하는 특징
    - 웹 브라우저에서 파일을 직접 열어도 내용을 확인 할 수 있고, 서버를 통해 뷰 템플릿을 거치면 동적으로 변경된 결과를 확인할 수 있다.
    (JSP를 포함한 다른 뷰 템플릿들은 해당 파일을 열면, 오직 서버를 통해서 JSP가 렌더링 되고 HTML 응답 결과를 받아야 화면을 확인 할 수 있음)
  • 스프링 통합 지원

 

타임리프 기본 기능

Tutorial: Using Thymeleaf

 

Tutorial: Using Thymeleaf

1 Introducing Thymeleaf 1.1 What is Thymeleaf? Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. The main goal of Thymeleaf is to provide a

www.thymeleaf.org

 

 

텍스트 - text

  • HTML 콘텐츠에 데이터를 출력할 때는 th:text 를 사용한다.
  • HTML 콘텐츠 영역 안에서 직접 데이털르 출력할 땐 [[${data}]] 를 사용
    <li>th:text 사용 <span th:text="${data}"></span></li>
    <li>컨텐츠 안에서 직접 출력하기 = [[${data}]]</li>

 

 

변수 - SringEL ${...}

    <li>${user.username} = <span th:text="${user.username}"></span></li>
    <li>${user['username']} = <span th:text="${user['username']}"></span></li>
    <li>${user.getUsername()} = <span th:text="${user.getUsername()}"></span></li>

모두 user.getUsername() 출력

 

th:with 를 사용하면 지역 변수를 선언해서 사용 할 수 있다.

<h1>지역 변수 - (th:with)</h1>
<div th:with="first=${users[0]}">
    <p>처음 사람의 이름은 <span th:text="${first.username}"></span></p>
</div>

user[0].username과 동일

 

 

기본 객체들

기존에 사용하는 것과 동일하게 기본 객체들을 제공한다.

 <li>request = <span th:text="${#request}"></span></li>
 <li>response = <span th:text="${#response}"></span></li>
 <li>session = <span th:text="${#session}"></span></li>
 <li>servletContext = <span th:text="${#servletContext}"></span></li>
 <li>locale = <span th:text="${#locale}"></span></li>
 <li>Request Parameter = <span th:text="${param.paramData}"></span></li> <!--param값 가져옴--->
 <li>session = <span th:text="${session.sessionData}"></span></li> <!--session값 가져옴-->
 <li>spring bean = <span th:text="${@helloBean.hello('Spring!')}"></span></li> <!--bean값에서 가져옴-->

 

 

유틸리티 객체와 날짜

Tutorial: Using Thymeleaf

 

Tutorial: Using Thymeleaf

1 Introducing Thymeleaf 1.1 What is Thymeleaf? Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. The main goal of Thymeleaf is to provide a

www.thymeleaf.org

 

 

URL 링크 @{...}

    <li><a th:href="@{/hello(param1=${param1}, param2=${param2})}">hello query param</a></li>

/hello?param1=data1&param2=data2

 

    <li><a th:href="@{/hello/{param1}/{param2}(param1=${param1}, param2=${param2})}">path variable</a></li>

/hello/data1/data2

 

    <li><a th:href="@{/hello/{param1}(param1=${param1}, param2=${param2})}">path variable + query parameter</a></li>

/hello/data1?param2=data2

 

 

리터럴

문자 리터럴엔 항상 작은 따옴표로 감싼다.

공백 없이 쭉 이어진다면 작은 따옴표 생략 가능함

    <li>'hello world!' = <span th:text="'hello world!'"></span></li>

리터럴 대체

    <li>리터럴 대체 |hello ${data}| = <span th:text="|hello ${data}|"></span></li>

 

 

속성 값 설정

속성 추가

  • th:attrappend : 속성 값의 뒤에 값을 추가
  • th:attrprepend : 속성 값의 앞에 값을 추가
  • th:classappend : class 속성에 자연스럽게 추가

checked 처리

:checked 속성이 있기 때문에 checked가 자동으로 처리.

 

 

반복

th:each 이용

 

 

주석

  1. 표준 HTML 주석
    :HTML 주석은 타임리프가 렌더링 하지 않고 ,그대로 남겨둔다.
  2. 타임리프 파서 주석
    :타임리프의 진짜 주석이다. 렌더링에서 주석 부분을 제거한다.
  3. 타임리프 프로토타입 주석
    :HTML 파일을 그대로 열어보면 주석 처리가 되지만, 타임리프를 렌더링 한 경우에만 보인다.
<h1>1. 표준 HTML 주석</h1>
<!--
<span th:text="${data}">html data</span>
-->
<h1>2. 타임리프 파서 주석</h1>
<!--/* [[${data}]] */-->
<!--/*-->
<span th:text="${data}">html data</span>
<!--*/-->
<h1>3. 타임리프 프로토타입 주석</h1>
<!--/*/
<span th:text="${data}">html data</span>
/*/-->

결과

<h1>예시</h1>
<span>Spring!</span>
<h1>1. 표준 HTML 주석</h1>
<!--
<span th:text="${data}">html data</span>
-->
<h1>2. 타임리프 파서 주석</h1>
<h1>3. 타임리프 프로토타입 주석</h1>
<span>Spring!</span>

 

 

블록 

<th:block> 타임리프의 유일한 자체 태그

div 여러개를 한번에 th:each 돌릴 때 사용

렌더링시 제거

<th:block th:each="user : ${users}">
    <div>
        사용자 이름1 <span th:text="${user.username}"></span>
        사용자 나이1 <span th:text="${user.age}"></span>
    </div>
    <div>
        요약 <span th:text="${user.username} + ' / ' + ${user.age}"></span>
    </div>
</th:block>

 

자바스크립트 인라인

<scrpit th:inline="javascript">

텍스트 렌더링

var username = [[${user.username}]];
  • 인라인 사용 전 var username = userA;
  • 인라인 사용 후 var username = "userA";

인라인 사용 후 렌더링 결과를 보면 문자 타입의 경우 "를 포함해준다. 추가로 자바스크립트에서 문제가 될 수 있는 문자가 포함되어 있으면 이스케이프 처리도 해준다.

 

자바스크립트 내추럴 템플릿

 var username2 = /*[[${user.username}]]*/ "test username";
  • 인라인 사용 전 var username2 = /*userA*/ "test username";
  • 인라인 사용 후 var username2 = "userA";

객체

객체를 JSON으로 자동 변환해준다.

 var user = [[${user}]];
  • 인라인 사용 전 var user = BasicController.User(username=userA, age=10);  //toString()이 호출 된 값 
  • 인라인 사용후 var user = {"username":"userA","age":10};

 

자바스크립트 인라인 each

<script th:inline="javascript">
 [# th:each="user, stat : ${users}"]
 var user[[${stat.count}]] = [[${user}]];
 [/]
</script>

 

 

템플릿 조각

:템플릿 조각과 레이아웃 조각

th:fragment : 다른 곳에 포함되어 있는 코드 조각

 

1.th:insert

<h2>부분 포함 insert</h2>
<div th:insert="~{template/fragment/footer :: copy}"></div>
  • th:footer = "copy"라는 부분을 템플릿 조각으로 가져와서 사용한다.
  • <div> 내부에 추가
<h2>부분 포함 insert</h2>
<div>
<footer>
푸터 자리 입니다.
</footer>
</div>

 

2.th:replace

<h2>부분 포함 replace</h2>
<div th:replace="~{template/fragment/footer :: copy}"></div>
<h2>부분 포함 단순 표현식</h2>
<div th:replace="template/fragment/footer :: copy"></div>

 

  • ~{...}이 원칙이지만 템플릿 조각을 사용하는 코드가 단순하면 생략할 수 있다.
  • 태그 <div>를 대체 한다.
<h2>부분 포함 replace</h2>
<footer>
푸터 자리 입니다.
</footer>

 

3.파라미터 사용

<h1>파라미터 사용</h1>
<div th:replace="~{template/fragment/footer :: copyParam ('데이터1', '데이터2')}"></div>
<footer th:fragment="copyParam (param1, param2)">
 <p>파라미터 자리 입니다.</p>
 <p th:text="${param1}"></p>
 <p th:text="${param2}"></p>
</footer>

 

 

템플릿 레이아웃

base

<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="common_header(title,links)">
    <title th:replace="${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}" />
</head>

layoutMain

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="template/layout/base :: common_header(~{::title},~{::link})">
    <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>

common_header(~{::title},~{::link}) → Main에서 title과 link가 공통 부분을 제외한 부분에서 자동 주입

 

결과

<!DOCTYPE html>
<html>
<head>
<title>메인 타이틀</title>
<!-- 공통 -->
<link rel="stylesheet" type="text/css" media="all" href="/css/awesomeapp.css">
<link rel="shortcut icon" href="/images/favicon.ico">
<script type="text/javascript" src="/sh/scripts/codebase.js"></script>
<!-- 추가 -->
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/themes/smoothness/jquery-ui.css">
</head>
<body>
메인 컨텐츠
</body>
</html>

 

 

 

'개발(~국비) > Spring' 카테고리의 다른 글

3.메시지,국제화  (0) 2022.11.21
2.타임리프-스프링 통합과 폼  (0) 2022.11.17
05.Spring-MVC)기본 기능  (0) 2022.11.05
04.Spring-MVC)MVC 구조의 이해  (0) 2022.11.04
03.Spring-MVC)MVC 프레임워크 만들기  (0) 2022.11.02