etc

[210527] Thymeleaf th:insert & th:replace

hjk927 2021. 5. 27. 01:06

 

.

 

jsp에는 forward, include같이 외부 파일의 코드를 현재 파일에 가져올 수 있는 기능이 있다. thymeleaf에서는 th:insert, th:replace가 그 역할을 한다. 이떄 jsp는 전체 코드만을 가져올 수 있는 반면에, 타임리프는 필요한 부분의 코드만 fragment(부분화)를 통해서 가져올 수 있다. 

 

※ fragment

th:fragment 태그를 사용해서 코드의 일부를 부분화할 수 있다. 

<nav class="navbar" id="mainNav">
    <div class="container" th:fragment="nav">
        ...
    </div>
</nav>

 

이렇게 작성하면, div 태그가 th:fragment 태그를 통해서 nav라는 이름으로 부분화 된 것이다. 부분화를 하면 코드를 쉽게 재사용할 수 있다. 

 

 

  • th:insert :  th:insert 태그가 선언된 태그 사이에 코드를 삽입한다. 
  • th:replace : th:replace가 쓰인 태그를 대체하고 코드를 삽입한다. 

 

- 예제 코드 

test.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  </head>
  <body>
    <span th:insert="/fragment::insert"></span>
    <span th:replace="/fragment::replace"></span>
  </body>
</html>

 

fragment.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <div th:fragment="insert">
        insert입니다.
    </div>
    <div th:fragment="replace">
        replace입니다.
    </div>
</html>

 

 

- 실행 결과

insert와 replace가 잘 된 걸 확인할 수 있다. 

insert의 경우, span 사이에 div 태그가 들어갔다. 

replace의 경우에는 기존에 test.html에 있던 span이 없어지고 replace로 첨부한 div만 남아있다. 

 

 

 

 

- 참고 자료

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

http://progtrend.blogspot.com/2019/05/thymeleaf.html