8.템플릿 프래그먼트

리얼브로·2023년 2월 24일
0

thymeleaf

목록 보기
8/10

여러 템플릿을 작성할 때 공통적인 내용을 별도 파일로 추출하여

효율적으로 사용할 수 있게 해주는 기능이다.

8-1. 프래그먼트 정의(th:fragment)

  • th:fragment 속성을 이용하여 공통적으로 사용할 부분을 프래그먼트로 정의한다.
  • [헤더 프레그먼트]

    <html xmlns:th="http://www.thymeleaf.org">
    
    <body>
    	<div th:fragment="header">
    		<p>페이지 헤더</p>
    	</div>
    </body>
    </html>
  • [푸터 프래그먼트]

    <html xmlns:th="http://www.thymeleaf.org">
    
    <body>
    	<div th:fragment="footer">
    		<p>© 2019 ALL RIGHT RESERVED</p>
    	</div>
    </body>
    </html>

8-2. 프래그먼트 참조

  • 정의한 프래그먼트를 참조해서 템플릿에 불러온다.

    <html>
    <head>
    	<title>Home</title>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
    	<div>
    		<p>페이지 헤더</p>
    	</div>
    	
    	<div>
    		<h1>Hello world!</h1>
    	</div>
    	
    	<div>
    		<p>© 2019 ALL RIGHT RESERVED</p>
    	</div>
    </body>
    </html>

8-3.th:insert

  • th:insert 속성을 이용하여 프래그먼트를 삽입한다.

  • [요청] http://localhost:8080/ch0808/home0101

  • [컨트롤러 메서드]

    @GetMapping("ch0808/home0101")
    public String home0101(Model model) {
      model.addAttribute("msg", "Hello world!");
    
      return "ch0808/home0101";
    }
  • [뷰 파일]

    <html xmlns:th="http://www.thymeleaf.org">
    
    <head>
    	<title>Home</title>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
    	<div th:insert="~{ch0808/fragments/header::header}"></div>
    	
    	<div>
    		<h1 th:text="${msg}">greeting</h1>
    	</div>
    	
    	<div th:insert="~{ch0808/fragments/footer::footer}"></div>
    </body>
    </html>
  • [응답 화면]

8-4.th:replace

  • th:replace 속성을 이용하여 프래그먼트를 대체한다.

  • insert 추가와 replace 교환은 타임리프 가 파싱 되고 나서 순수 html 코드 소스 보기 하면
    처리된 내용이 다르다. (insert 일 경우 html 요소가 추가되는 차이)

  • [요청] http://localhost:8080/ch0808/home0201

  • [컨트롤러 메서드]

    @GetMapping("ch0808/home0201")
    public String home0201(Model model) {
      model.addAttribute("msg", "Hello world!");
    
      return "ch0808/home0201";
    }
  • [뷰 파일]

    <html xmlns:th="http://www.thymeleaf.org">
    
    <head>
    	<title>Home</title>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
    	<div th:replace="~{ch0808/fragments/header::header}"></div>
    	
    	<div>
    		<h1 th:text="${msg}">greeting</h1>
    	</div>
    	
    	<div th:replace="~{ch0808/fragments/footer::footer}"></div>
    </body>
    </html>
  • [응답 화면]

0개의 댓글