Skip to content
Henrik Vendelbo edited this page Jun 4, 2013 · 10 revisions

HTML5 has a basic templating element built in. Add a template tag to your page and you will be able to reuse the content in any element of the page by referring to the template.

Regardless of the browser EssentialJS allows you to add template elements using role="template". The Resolver("templates") will give you a place to look up a template object for a predefined template. It leverages the HTMLSnippet functionality to instantiate a branch of DOM elements.

var myTemplate = Resolver("templates")("#abc");

will define a template reference for the template element with the id "abc". Equally Resolver("templates")(".def") will return a template for the template element with the class "abc".

will loaded in the main page or a subsidiary page define a template that can be referenced by abc. The template can be used by a simple call to the clone function.

parentEl.appendChild(myTemplate.content.cloneNode(true));

Before cloning the template you can set values through element proxies by calling querySelector on the template, these modifications are queued up and applied in cloneNode. For native template element the native calls are used.

myTemplate.content.querySelector("img").src = "abc.png";
parentEl.appendChild(myTemplate.content.cloneNode(true));

Note the img tag. Media elements such as img, audio, video and object can have src attributes without attempting to load the content in older browsers.

Note that in browsers that do not natively support HTML5 template tags you cannot put one inside a table, as the browser enforces a strict semantic. You can of couse turn a valid element into a template such as,

<table>
<tr role="template" id="my-row"></tr>
</table>

However for tables there is a special Templating Tables support for those particular cases.

Note that there is no support for <style> elements in browsers that don't support templates natively.

Clone this wiki locally