템플릿 레이아웃 1. - tag 넘기기

알파로그·2023년 3월 25일
0

Spring MVC 활용 기술

목록 보기
17/42
  • fragment 는 변수, 객체 뿐 아니라 html 의 tag 도 넘겨줄 수 있다.

✏️ 템플릿 레이아웃 사용하기

📍 fragment 생성

  • 생성 방법은 일반적인 fragment 생성방법과 동일하다.
    • 매개변수는 th:옵션="${매개변수}" 의 형태로 사용할 수 있다.
    • 옵션 은 fragment 의 호출방법인 replace, insert 를 사용하면 된다.
    • 예제에서는 타이틀과 추가 부분만 파라미터를 통해 동적으로 구현했고,
      나머지 공통부분은 어떻게 호출하든 동일하게 출력될 수 있게 구현했다.
<head th:fragment="common_header(title,links)">

    <title th:replace="${title}">매개변수 사용</title>

    <!-- 공통 -->
    <link rel="stylesheet" type="text/css" media="all" th:href="@{/css/awesomeapp.css}">

    <link rel="shortcut icon" th:href="@{/images/favicon.ico}">

    <script type="text/javascript" th:src="@{/sh/scripts/codebase.js}"></script>

    <!-- 추가 -->
    <th:block th:replace="${links}"/>
</head>

📍 fragment 사용

  • ~{::태그명} 의 형태로 파라미터를 넘겨주면 된다.
    • replace 의 파라미터에 title 태그와 link 태그를 넘겨주었다.
    • web page 에서는 fragment 를 사용한 head 태그 내의 태그들은 fragment 와 합체된 상태로 보여지게 된다.
<head th:replace="template/layout/base :: common_header(~{::title},~{::link})">

    <title>메인 타이틀</title>
    <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
    <link rel="stylesheet" th:href="@{/themes/smoothness/jquery-ui.css}">

</head>

📍 소스 확인

  • fragment 의 변수로 title 이 변경되었다.
  • 공통로직은 fragment 그대로 출력되었다.
  • 추가로직은 fragment 의 변수로 변경되었다.
<head>
    <title>메인 타이틀</title>

    <!-- 공통 -->
    <link rel="stylesheet" type="text/css" media="all" href="/css/awesomeapp.css">

    <link rel="shortcut icon" href="/images/favicon.ico">

    <script type="text/javascript" src="/sh/scripts/codebase.js"></script>

    <!-- 추가 -->
    <link rel="stylesheet" href="/css/bootstrap.min.css"><link rel="stylesheet" href="/themes/smoothness/jquery-ui.css">
</head>
profile
잘못된 내용 PR 환영

0개의 댓글