스프링 MVC 2편(백엔드 웹 개발 활용 기술)

Ch01. 타임리프(기본 기능) - 템플릿 조각

webmaster 2022. 3. 10. 12:09
728x90
@Controller
@RequestMapping("/template")
public class TemplateController {
    @GetMapping("/fragment")
    public String template(){
        return "template/fragment/fragmentMain";
    }
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<h1>부분 포함</h1>
<h2>부분 포함 insert</h2>
<div th:insert="~{template/fragment/footer :: copy}"></div>
<h2>부분 포함 replace</h2>
<div th:replace="~{template/fragment/footer :: copy}"></div>
<h2>부분 포함 단순 표현식</h2>
<div th:replace="template/fragment/footer :: copy"></div>
<h1>파라미터 사용</h1>
<div th:replace="~{template/fragment/footer :: copyParam ('데이터1', '데이터2')}"></div>
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<footer th:fragment="copy">
  푸터 자리 입니다.
</footer>
<footer th:fragment="copyParam (param1, param2)">
  <p>파라미터 자리 입니다.</p>
  <p th:text="${param1}"></p>
  <p th:text="${param2}"></p>
</footer>
</body>
</html>
  • 부분 포함 Insert
    • <div th:insert="~{template/fragment/footer :: copy}"></div>
    • 현재 태그(div) 내부에 추가를 한다
  • 부분 포함 replace
    • <div th:replace="~{template/fragment/footer :: copy}"></div>
    • 현재 태그(div)를 대체한다.
  • 부분 포함 단순 표현식
    • <div th:replace="template/fragment/footer :: copy"></div>
    • ~{..}를 사용하는 것이 원칙이지만 코드가 단순하면 생략이 가능하다
  • 파라미터 사용
    • <div th:replace="~{template/fragment/footer :: copyParam ('데이터 1', '데이터 2')}"></div>
    • 파라미터를 전달하여 동적으로 조각 레터링이 가능하다
728x90