HTML 컨텐츠 템플릿 (
<template>
) 엘리먼트는 페이지에 로드될 때 렌더링되지 않지만 JavaScript 를 사용하는 런타임동안에 후속적으로 인스턴트화되는 클라이언트 사이드 컨텐츠를 유지하기 위한 메커니즘입니다.
이는 다큐먼트에서 나중에 사용하기 위해 저장하는 컨텐츠 조각으로 생각하시면 됩니다. 페이지가 로딩되는 동안 파서가 <template>
엘리먼트의 컨텐츠를 처리하지만, 컨텐츠가 유효한지만 확인합니다. 엘리먼트의 컨텐츠는 렌더링되지 않습니다.
-
컨텐츠 카테고리 메타데이터 컨텐츠, 플로우 컨텐츠, 파싱 컨텐츠, 스크립트 지원 엘리먼트 허용된 컨텐츠 제한 없음 태그 생략 None, both the starting and ending tag are mandatory. 허용된 부모 <body>
,<frameset>
,<head>
,<dl>
및span
어트리뷰트가 없는<colgroup>
허용된 ARIA 역할 없음 DOM 인터페이스
어트리뷰트
이 엘리먼트는 전역 어트리뷰트만 포함합니다.
예제
먼저 예제의 HTML 일부를 통해 시작하겠습니다.
<table id="producttable"> <thead> <tr> <td>UPC_Code</td> <td>Product_Name</td> </tr> </thead> <tbody> <!-- 존재하는 데이터는 선택적으로 여기에 포함됩니다 --> </tbody> </table> <template id="productrow"> <tr> <td class="record"></td> <td></td> </tr> </template>
먼저, 나중에 JavaScript 코드를 사용해 컨텐츠를 삽입할 테이블이 있습니다. 그 다음 테이블의 열을 표현하는 HTML 조각의 구조를 설명하는 템플릿이 옵니다.
이제 테이블이 생성되었고 템플릿이 정의되었으므로, JavaScript 를 사용해 템플릿을 사용해 구성된 열을 기반으로 각 열을 테이블로 삽입합니다.
// 템플릿 엘리먼트의 컨텐츠 존재 유무를 통해
// 브라우저가 HTML 템플릿 엘리먼트를 지원하는지 확인합니다
if ('content' in document.createElement('template')) {
// 기존 HTML tbody 와 템플릿 열로 테이블을 인스턴스화합니다
var t = document.querySelector('#productrow');
// 새로운 열을 복제하고 테이블에 삽입합니다
var tb = document.querySelector("tbody");
var clone = document.importNode(t.content, true);
td = clone.querySelectorAll("td");
td[0].textContent = "1235646565";
td[1].textContent = "Stuff";
tb.appendChild(clone);
// 새로운 열을 복제하고 테이블에 삽입합니다
var clone2 = document.importNode(t.content, true);
td = clone2.querySelectorAll("td");
td[0].textContent = "0384928528";
td[1].textContent = "Acme Kidney Beans 2";
tb.appendChild(clone2);
} else {
// HTML 템플릿 엘리먼트를 지원하지 않으므로
// 테이블에 열을 추가하는 다른 방법을 찾습니다.
}
결과는 JavaScript 를 통해 추가된 두 개의 새로운 열을 포함하는 기존 HTML 테이블입니다.
table {
background: #000;
}
table td {
background: #fff;
}
명세
명세 | 상태 | 코멘트 |
---|---|---|
HTML Living Standard The definition of 'template element' in that specification. |
Living Standard | |
HTML5 The definition of 'template element' in that specification. |
Recommendation | 초기 정의 |
브라우저 호환성
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
template | Chrome Full support 26 | Edge Full support 13 | Firefox Full support 22 | IE No support No | Opera Full support 15 | Safari Full support 8 | WebView Android Full support Yes | Chrome Android Full support 26 | Firefox Android Full support 22 | Opera Android ? | Safari iOS Full support 8 | Samsung Internet Android Full support 1.5 |
Legend
- Full support
- Full support
- No support
- No support
- Compatibility unknown
- Compatibility unknown
함께 보기
- 웹 컴포넌트:
<slot>
(그리고 역사적으로:<shadow>
) - 템플릿과 슬롯 사용하기