Template Literal expressions within the Template tag seem like a missed opportunity

davecranwell

Dave Cranwell

Posted on January 11, 2019

Template Literal expressions within the Template tag seem like a missed opportunity

Template Literals are amazing, but I've lately found they make everything look like a proverbial nail, particularly when it comes to updating large blocks of HTML dynamically.

I'm still working in an environment which is mostly backend, where Perl generates HTML from templates, on top of which we add progressively enhanced javascript components.

When both your back and front end need to be able to generate common UI patterns based on a pattern library, it becomes frustrating to have to define the HTML source for each UI pattern in multiple places (once in Perl, once in JS).

The <template> tag could be useful. The backend can generate the HTML required for the component (e.g each Todo item in the Todo list) and the JS can use that HTML template to generate each new todo item.

But the only way of dynamically inserting values into that template, that I'm aware of, is with the extraordinarily clumsy use of CSS selectors in the template content. (see: https://blog.teamtreehouse.com/creating-reusable-markup-with-the-html-template-element)

Wouldn't it make so much more sense, now Template Literals are in every major browser, to add support within the <template> API for expressions? e.g

<template id="test-template">
    hello ${where}
</template>
Enter fullscreen mode Exit fullscreen mode
const tmpl = document.getElementById('test-template');

// where "MAGIC" is some means of supplying data as json 
document.body.appendChild(tmpl.content.cloneNode(true, MAGIC));
Enter fullscreen mode Exit fullscreen mode

Web Components have the <slot> system, but that requires the adoption of a much larger tech. And, yes, there's always Mustache/Handlebars et al, but again that's adding to the JS payload. Yes we also use React, but upgrading everything to React isn't always possible.

Am I alone in trying to make this work? Anyone found a framework-free or framework-lite solution for this?

💖 💪 🙅 🚩
davecranwell
Dave Cranwell

Posted on January 11, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related