HTML Templates

The HTML `<template>` element represents a template in your markup. It contains "template contents"; essentially inert chunks of cloneable DOM.

Think of templates as pieces of scaffolding that you can use (and reuse) throughout the lifetime of your app. HTML Templates are one of the four pillars of the Web Components HTML5 standard.

# Browser coverage

HTML Templates are supported in the latest desktop and mobile browsers - caniuse.com

# Use

HTML template is a way to create insert chunks of HTML that are stamped at will. The syntax of HTML templates look like this:

<html> <template> <p>The HTML you wish to instantiate at will</p> </template> </html>

Scripts will not run, and resources that are inside a template will not be fetched until the template is stamped out - webcomponents.org

YOUTUBE qC5xK6H0GlQ Web Components are a set of technologies that changes the way you develop web apps entirely. By making components scoped and reusable in standardized way, your web development will step up to the next level. In this video, you will learn how to work with Template.

To create a templated content, declare some markup and wrap it in the <template> element:

<template id="mytemplate"> <img src="" alt="great image"> <div class="comment"></div> </template>

The observant reader may notice the empty image. That's perfectly fine and intentional. A broken image won't 404 or produce console errors because it won't be fetched on page load. We can dynamically generate the source URL later on - html5rocks

# The pillars

Wrapping content in a <template> gives us few important properties.

- Its content is effectively inert until activated. Essentially, your markup is hidden DOM and does not render. - Any content within a template won't have side effects. Script doesn't run, images don't load, audio doesn't play,...until the template is used. - Content is considered not to be in the document. Using document.getElementById() or querySelector() in the main page won't return child nodes of a template. - Templates can be placed anywhere inside of <head>, <body>, or <frameset> and can contain any type of content which is allowed in those elements. Note that "anywhere" means that <template> can safely be used in places that the HTML parser disallows...all but content model children. It can also be placed as a child of <table> or <select>:

<table> <tr> <template id="cells-to-repeat"> <td>some content</td> </template> </tr> </table>

# See also - Polymer - template.js - github - Template engines - zellwk.com