HTML's New Template Tag
The concept of templating is not new to web development. In fact, server-side
templating languages/engines like Django (Python), ERB/Haml (Ruby), and Smarty (PHP)
have been around for a long time. In the last couple of years however, we've seen
an explosion of MVC frameworks spring up. All of them are slightly different,
yet most share a common mechanic for rendering their presentational layer (aka da view): templates.
Let's face it. Templates are fantastic. Go ahead, ask around. Even its definition makes you feel warm and cozy:
template (n) - A document or file having a preset format, used as a starting point for a particular application so that the format does not have to be recreated each time it is used.
"…does not have to be recreated each time…" Don't know about you, but I love
avoiding extra work. Why then does the web platform lack
native support for something developers clearly care about?
The WhatWG HTML Templates specification is the answer. It defines a
new
element which describes a standard DOM-based approach
for client-side templating. Templates allow you to declare fragments of markup which are parsed as HTML, go unused at page load, but can be instantiated
later on at runtime. To quote Rafael Weinstein:
They're a place to put a big wad of HTML that you don't want the browser to mess with at all…for any reason.
Feature Detection
To feature detect
, create the DOM element and check that the
.content property exists:
function supportsTemplate() {
return 'content' in document.createElement('template');
}
if (supportsTemplate()) {
// Good to go!
} else {
// Use old templating techniques or libraries.
}
Declaring template content
The HTML
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.
To create a templated content, declare some markup and wrap it in the
element:
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.
The pillars
Wrapping content in a
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
,
, or