HTML5 template tag hello world tutorial

HTML5 template tag can be used to define template in html and instantiate it when needed. The instantiated template can be inserted in any DOM element using appendChild.
html5-tempate-tag

template tag example using vanilla Javascript

<template id="t1">
  <div>Template instance: <span class="instance-num">0</span></div>
</template>
<div id="container"><div>Some content</div></div>
<script type="text/javascript">
window.addEventListener("load", init);
function init() {
  for(var i=0; i < 3; i++) {
    var content = document.querySelector('#t1').content;
    var span = content.querySelector('.instance-num');
    span.textContent = i;
    document.querySelector('#container').appendChild(
      document.importNode(content, true));
  }
}
</script>
refresh

Few points to note about template

  1. .content property can be used to get content of a template dom element.
  2. document.importNode(content, true) imports template content with depth=true to include its children.
  3. template tag is supported by Chrome and Firefox and not by IE. One can see more info at template tag support.
  4. Images etc. in template are not loaded till template is cloned/instantiated.

Specification and Browser compatibility

SpecificationStatusCategories
HTML templatesWHATWG Living StandardDOM, HTML5
Desktop
ChromeFirefoxIEEdgeSafariOpera
Yes 26+ Yes 22+ NoYes 13+ Yes 7.1+ Yes 15+
Mobile
Android ChromeAndroid FirefoxiOS SafariIE MobileOpera Mobile
Yes 47+ Yes 44+ Yes 8+ NoYes 33+
source: caniuse.com
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments