파란하늘의 지식창고
article thumbnail
반응형

thymeleaf도 하도 오래간만에 보니 새로 배우는 느낌이어서 정리하면서 써보려고 한다.

FE, BE가 완전히 분리되지 않는다는 게 단점이지만 반대로 보면 Thymeleaf가 BE와 연동이 매우 쉽다는 것이 장점이기도 하다.

Spring Boot에서 Thymeleaf 사용하기

기본 사용

Spring Boot에서 Thymeleaf를 사용하려면 다음 dependency를 추가하면 된다.

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-thymeleaf</artifactId> 
</dependency>

이 dependency를 추가하면 Spring Boot AutoConfigure는 Thymeleaf를 사용할 수 있는 기본적인 설정을 제공해 준다.
현재 spring-boot-starter-thymeleaf는 thymeleaf-spring6을 기본 참조하고 있다.

그다음 호출할 Controller를 만든다.

@Controller 
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE) 
public class IndexController { 
    @GetMapping({"/", "/index"}) 
    public String index() { 
        return "index"; 
    } 
}

String으로 "index"란 이름을 반환하였는데 /templates/index.html을 찾으라는 의미이다.
Controller의 문자열 반환의 경우 암묵적으로 template의 위치나 redirect, forward 설정을 찾는다.

이제 thymeleaf를 사용하는 페이지를 만든다.
해당 리소스의 위치는 /src/main/resources/templates 하위이다.

기본 위치를 바꾸고 싶다면 아래 설정의 기본값을 다른 값으로 지정하면 되지만 굳이 바꿔야 할 경우는 거의 없을 것 같다.

spring.thymeleaf.prefix=classpath:/templates/

정적 리소스의 경우 /src/main/resources/static 하위에 위치한다.

templates 아래 index.html을 만들어본다.
xmlns는 따로 자동완성을 지원하는 스키마는 아니고 단지 th로 시작하는 attribute를 사용할 때 뜨는 알럿을 보지 않기 위해 설정한다.

<!DOCTYPE html> 
<html xmlns:th="http://www.thymeleaf.org"> 
<body> 
index 
</body> 
</html>

서버를 띄우고 호출해 보면 화면이 잘 뜬다.
하지만 thymeleaf의 내용을 수정하면 수정이 바로 반영되지 않는다.

개발 시엔 Thymeleaf 렌더링에 대한 캐시를 비활성화하여야 thymeleaf HTML 페이지의 수정이 바로바로 반영된다.
라이브 상황에는 활성화해주어야 한다.
아래처럼 설정해 준다.

spring.thymeleaf.cache=false

thymeleaf-layout-dialect 사용하기

https://www.thymeleaf.org/doc/articles/layouts.html

위에서 기본적인 HTML 페이지는 호출을 해보았다.
HTML 페이지는 Controller의 @RequestMapping 설정과 연동하여 호출할 주소가 많아지면 많아질수록 계속 만들게 되는데 점점 많은 페이지를 만들게 될 것이다.
이렇게 많아지면 보통 레이아웃을 구성하여 여러 페이지들에서 공통으로 사용하는 코드를 재사용하게 된다.

th:insert, th:replace, th:fragment를 통한 재사용은 Thymeleaf에서 기본적으로 제공해주고 있다.
하지만 이것으로는 충분하지 않다.

Thymeleaf는 Dialect라는 개념을 제공하는데 이를 통해 Thymeleaf의 기본 사용을 확장하여 사용할 수 있게 된다.
그중 가장 많이 사용하는 것이 Layout Dialect인데 레이아웃 구성을 사용할 수 있게 확장해 주는 라이브러리이다.

https://www.thymeleaf.org/doc/articles/layouts.html#thymeleaf-layout-dialect

다음과 같이 dependency를 추가한다.

<dependency> 
  <groupId>nz.net.ultraq.thymeleaf</groupId> 
  <artifactId>thymeleaf-layout-dialect</artifactId> 
</dependency>

이제 적절하게 layout을 모아두는 /templates/layout 디렉터리를 만들고 defaultLayout.html을 아래처럼 만들었다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

<body>
	<div>상단</div>
	<div layout:fragment="content">본문</div>
	<div>하단</div>
</body>

</html>

그리고 아까 만들었던 index.html에서 layout을 사용하도록 설정한다.
html 태그의 layout:decorate로 사용할 layout을 설정하고 layout:fragment 속성을 지정하여 대체할 부분을 선언한다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
    layout:decorate="~{layout/defaultLayout}">

<body>
    <div layout:fragment="content">
        index 본문
    </div>
</body>

</html>

해당 페이지를 호출하면 아래처럼 layoutDefault.html 안에 본문 부분이 index.html의 내용이 들어가 있는 상태로 응답을 하게 된다.

상단
index 본문
하단

thymeleaf-extras-springsecurity6 사용하기

thymleaf는 Spring Security관련한 지원도 간단하게 사용할 수 있다.

https://www.thymeleaf.org/doc/articles/springsecurity.html

다음 dependency를 추가하면 된다.

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>

sec:authorize, sec:authentication으로 아래와 같은 다양한 사용을 할 수 있다.

<div sec:authorize="isAuthenticated()">
  This content is only shown to authenticated users.
</div>
<div sec:authorize="hasRole('ROLE_ADMIN')">
  This content is only shown to administrators.
</div>
<div sec:authorize="hasRole('ROLE_USER')">
  This content is only shown to users.
</div>

Logged user: <span sec:authentication="name">Bob</span>
Roles: <span sec:authentication="principal.authorities">[ROLE_USER, ROLE_ADMIN]</span>

thymeleaf-extras-data-attribute 사용하기

data attribute는 html 태그에서 표준이 아닌 속성이나 추가적인 DOM 속성을 지정하여 사용할 때 사용한다.

"data-"로 시작하는 속성에 값을 담아두는 데 아래처럼 사용한다.

<article
  id="electriccars"
  data-columns="3"
  data-index-number="12314"
  data-parent="cars">
...
</article>

thymeleaf-extras-data-attribute는 이 data-attribute를 쉽게 사용할 수 있도록 도와준다.

https://github.com/mxab/thymeleaf-extras-data-attribute

다음 dependency를 추가한다.

<dependency>
    <groupId>com.github.mxab.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-data-attribute</artifactId>
</dependency>

아래와 같이 설정하면

<html>
<body data:foo="${'bar'}" data:msg="#{my.message}" >
</body>
</html>

다음과 같이 렌더링 된다.

<html>
<body data-foo="bar" data-msg="Your resolved message" >
</body>
</html>

 

반응형
profile

파란하늘의 지식창고

@Bluesky_

내용이 유익했다면 광고 배너를 클릭 해주세요