Template Block

Web Component
JavaScript
GitHub Gist

What It Is

A very simple way to template HTML

Status

I wrote it in about two minutes. Seems to work fine.

Details

This is a very simple way to template HTML in the browser.

Surround a block of HTML with elements to be replaced by variable data. The elements should have a data-key attribute with a unique key.

<template-block>
  My name is <span data-key="first"/> <span data-key="last"/>
</template-block>

Then, from JavaScript, simply call render with an object containing properties that match the keys. Also, include a boolean _display property which indicates if the block should be displayed (it is not displayed by default).

myTemplateBlock.render({
  _display: firstName.length > 0,
  first: firstName,
  last: lastName
});

The values of the object properties will become the innerHTML of the elements with the matching data-key attributes.

There is no logic. It’s expected you will do all the logic and formatting in the object you pass into render.

A block will recurse through nested template-block elements, rendering each with the object in that property name as its top-level context.

<template-block>
  <p>My name is <span data-key="name"></span>.<p>
  <template-block data-key="age">
    <p>I am <span data-key="value"></span> <span data-key="unit"></span> old.</p>
  </template-block>
</template-block>
myTemplateBlock.render({

  _display: name.length > 0,
  name: name,
  age {
    _display: age > 0,
    value: age,
    unit: age != 1 ? "years" : "year"
  }

})

So the inner template-block in the example above will get be rendered with the object in the age property, meaning its token effectively gets age.value.

That’s all it does.

(It doesn’t iterate, because I haven’t needed it to. But I do have a system mentally sketched out that would work pretty well for looping over arrays. Someday I’ll need it.)