front/HTML, CSS

[thymeleaf] 템플릿 조각 (layout)

배고파요 2024. 7. 10. 16:58
728x90

- 기존 jsp 에서는 tiles 라는 것을 이용해서 header, content, footer 등을 연결시킬 수 있었는데, 
타임리프에는 템플릿 조각을 이어서 만들 수 있다.

 

📍 layout.html

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

<head>
    <title layout:title-pattern="$LAYOUT_TITLE :: $CONTENT_TITLE">공동 타이틀</title>
    <th:block th:replace="~{common/config :: config}" />
</head>

<body>
<!-- header -->
<header th:replace="common/header::header"></header>

<!-- content -->
<th:block layout:fragment="content"></th:block>

<!-- footer -->
<footer th:replace="common/footer::footer"></footer>
</body>
</html>

 

 

📍 header.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<th:block th:fragment="header">
<script type="text/javascript" th:inline="javascript">
    $(function(){
        console.log("header-----");
    });
    function changeLanguage(){
        $.ajax({
            url : "/changeLanguage",
            type : "post",
            data : {
                lang : $("select[name=lang]").val()
            },
            success: function(data) {
                console.log("언어 testee변환");
                location.reload(true);
            },
            error: function() {
                alert("요청 처리 중 오류가 발생하였습니다! \n관리자에게 문의하세요!");
            }
        });
    }
</script>
<body>
    <label>
        <select name="lang" onchange="changeLanguage();">
            <option th:each="language : ${languageEnum}"
                    th:value="${language.code}"
                    th:text="${language.displayName}"
                    th:selected="${changeLanguage.lang.contains(language.code)}">
            </option>
        </select>
    </label>

    <div>
        <h1 th:text="#{hello}"></h1>
        <h1 th:text="#{hello.title}"></h1>
    </div>
</body>
</th:block>
</html>

 

 

📍 footer.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div th:fragment="footer">푸터1111</div>
</body>
</html>

 

 

 

📍 content 영역

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


<head>
    <title layout:fragment="title">detail 상세페이지</title>
</head>
<th:block layout:fragment="content">
<body>
    <div>

        <h1 th:text="content영역"></h1>

    </div>
</body>

</th:block>
</html>

 

 

 

+) content 영역에 다른 것을 넣게 되면, 모든 템플릿 조각을 다시 로드함.


출처 : 

 

 

 


개발 공부를 위한 블로그 입니다. 

오류가 있다면 댓글로 알려주세요! 

감사합니다.

728x90