HTML <template> 태그

정의와 사용법

<template> 태그를 사용하여 페이지 로드 시 사용자에게 숨겨질 HTML 내용을 담을 수 있습니다.

<template> 내용은 나중에 JavaScript를 사용하여 표시할 수 있습니다.

또한, 필요할 때만 표시할 수 있는 반복되는 HTML 코드가 있다면, <template> 태그 없이 <template> 태그를 사용하려면, 브라우저가 코드를 표시하지 않도록 HTML 코드를 생성하는 JavaScript를 사용해야 합니다.

예제

예제 1

사용 <template> 페이지 로드 시 숨겨질 내용을 저장하고 JavaScript를 사용하여 그것을 표시하십시오:

<button onclick="showContent()">숨겨진 내용 보여주기</button>
<template>
  <h2>Flower</h2>
  <img src="img_white_flower.jpg" width="214" height="204">
</template>
<script>
function showContent() {
  var temp = document.getElementsByTagName("template")[0];
  var clon = temp.content.cloneNode(true);
  document.body.appendChild(clon);
}
</script>

직접 시험해 보세요

예제 2

数组의 각 항목에 새로운 div 요소를 사용하여 웹 페이지를 채우십시오. 각 div 요소의 HTML 코드는 template 요소 내에 있습니다:

<template>
  <div class="myClass">I like: </div>
</template>
<script>
var myArr = ["Audi", "BMW", "Ford", "Honda", "Jaguar", "Nissan"];
function showContent() {
  var temp, item, a, i;
  temp = document.getElementsByTagName("template")[0];
  item = temp.content.querySelector("div");
  for (i = 0; i < myArr.length; i++) {
    a = document.importNode(item, true);
    a.textContent += myArr[i];
    document.body.appendChild(a);
  }
}
</script>

직접 시험해 보세요

예제 3

브라우저의 <template> 지원:

<script>
if (document.createElement("template").content) {
  document.write("Your browser supports template!");
} else {
  document.write("Your browser does not supports template!");
}
</script>

직접 시험해 보세요

전역 속성

<template> 태그는 다음과 같은 속성을 지원합니다 HTML의 전역 속성

브라우저 지원

표의 숫자는 이 속성을 최초로 완전히 지원하는 브라우저 버전을 나타냅니다.

크롬 에지 파이어폭스 사파리 오페라
크롬 에지 파이어폭스 사파리 오페라
26.0 13.0 22.0 8.0 15.0