Getting Start HTML's Template

Oct 28, 2014

Outline

We’ve used html template when we develop web app by using some tricks.

But now we can use template function safely and conveniently if you use new Template.

Capability

can i use : http://caniuse.com/#feat=template

At the moment (2014/10/27) we can not use it only IE. In all of modern browser we can use it.

Benefit

Usage

If you have following template you can use it with 2 ways below.

<template id="mytemplate">
	<div class="comment">this is new contents generated from template element.</div>
</template>

<section id="host"></section>

basic

var t = document.querySelector('#mytemplate');
var host = document.querySelector('#host');
var clone = document.importNode(t.content, true);

host.appendChild(clone);

with shadow dom

var t = document.querySelector('#mytemplate');
var host = document.querySelector('#host-target').createShadowRoot();
var clone = document.importNode(t.content, true);

host.appendChild(clone);

Reference