Skip to content
Henrik Vendelbo edited this page Apr 24, 2014 · 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("document::essential.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("document::essential.templates")(["#abc"]);

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

<template id="abc">hello</template>

will loaded in the main page or a subsidiary page define a template that can be referenced by abc. As an alternative you can use <div role="template">hello</div>. 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.

Easy table row templating

<table>
  <tr><th>First</th><th>Second</th></tr>
  <tr role="template"><td>1</td><td>2</td></tr>
</table>

The template row element has no identification and is the last row in the table. In this case the row will be repeated as needed. (TODO expand)

Clone this wiki locally