템플릿 상속

prana·2023년 5월 23일

SpringBoot

목록 보기
14/22
post-thumbnail

태그와 엘리먼트

<table>은 table 태그이고, <table>~</table> 태그로 시작해 태그로 닫힌 구간(Block)은 table 엘리먼트이다.

// 표준 HTML 구조의 예 
<!doctype html>
<html lang="ko">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" type="text/css" th:href="@{/bootstrap.min.css}">
    <!-- sbb CSS -->
    <link rel="stylesheet" type="text/css" th:href="@{/style.css}">
    <title>Hello, sbb!</title>
</head>
<body>
(... 생략 ...)
</body>
</html>
  • css 파일은 head 엘리먼트 안에 링크되어야 한다.

  • head 엘리먼트 안에는 meta, title 엘리먼트 등이 포함되어야 한다.

  • 표준 HTML 구조로 변경하면, body 엘리먼트 바깥 부분은 모두 같은 내용으로 중복된다.

    템플릿 상속은 기본 틀이 되는 템플릿을 먼저 작성하고, 다른 템플릿에서 그 템플릿을 상속해 사용하는 방법이다.


/sbb/src/main/resources/templates/layout.html

<!doctype html>
<html lang="ko">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" type="text/css" th:href="@{/bootstrap.min.css}">
    <!-- sbb CSS -->
    <link rel="stylesheet" type="text/css" th:href="@{/style.css}">
    <title>Hello, sbb!</title>
</head>
<body>
<!-- 기본 템플릿 안에 삽입될 내용 Start -->
✅<th:block layout:fragment="content"></th:block>
<!-- 기본 템플릿 안에 삽입될 내용 End -->
</body>
</html>

layout.html 템플릿을 상속하면,
<th:block layout:fragment="content"></th:block> 에 해당되는 부분만 작성해도
표준 html 문서가 된다.


question_list.html 수정

<!DOCTYPE html>
<html layout:decorate="~{layout}" xmlns:layout="http://www.w3.org/1999/xhtml" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div layout:fragment="content" class="container my-3">
<table class="table">
    <thead class="table-dark">
    <tr>
        <th>번호</th>
        <th>제목</th>
        <th>작성일시</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="question, loop : ${questionList}">
        <td th:text="${loop.count}"></td>
        <td>
            <a th:href="@{|detail/${question.id}|}" th:text="${question.subject}"></a>
        </td>
        <td th:text="${#temporals.format(question.createDate, 'yyyy-MM-dd HH:mm')}"></td>
    </tr>
    </tbody>
</table>
</div>
</body>
</html>

출처 : https://wikidocs.net/161523

0개의 댓글