From the one of answer to Creating a new DOM element from an HTML string using built-in DOM methods or Prototype question:
Most current browsers support HTML elements, which provide a more reliable way of turning creating elements from strings.
Well, but generally it's useless to retrieve the template
element without interpolating some data into it. But how to do it?
Concrete example
Retrieve below template from DOM and fill h1
and p
elements by the data. It's allowed to modify the template
tag content to make the access to elements easier, but let me repeat: please, no frameworks.
<template id="CatCardTemplate">
<div class="CatCard">
<h1></h1>
<p></p>
</div>
</template>
DOM manipulation solution
In the MDN example, the interpolation is being provided by DOM manipulations:
var tbody = document.querySelector("tbody");
var template = document.querySelector('#productrow');
var clone = template.content.cloneNode(true);
var td = clone.querySelectorAll("td");
td[0].textContent = "1235646565";
td[1].textContent = "Stuff";
tbody.appendChild(clone);
var clone2 = template.content.cloneNode(true);
td = clone2.querySelectorAll("td");
td[0].textContent = "0384928528";
td[1].textContent = "Acme Kidney Beans 2";
tbody.appendChild(clone2);
I can't believe if it's best that we can in 2021 without frameworks.
My efforts: musings about Handlebars solution
Because Handlebars is not a framework, it's allowed alternative. If Handlebars code is a valid HTML, we can use it inside template elements:
<template id="CatCardTemplate">
<div class="CatCard">
<h1>{{name}}</h1>
<p>Age: {{age}}</p>
</div>
</template>
Now we can pick up the template and interpolate the data by Handlebars:
/*
* ⇩ Works, but causes "ModuleNotFoundError: Module not found: Error: Can't resolve 'fs' in ...".
* It's knows issue but I did not fount the acceptable solution yet.
* @see https://github.com/handlebars-lang/handlebars.js/issues/1174
*/
import Handlebars from "handlebars";
type CatData = {
name: string;
age: number;
};
const catCardTemplate: HTMLTemplateElement | null = document.getElementById<HTMLTemplateElement>("CatCardTemplate");
// Handle null case...
const renderCatCard: Handlebars.TemplateDelegate<Cat> = Handlebars.compile(catCardTemplate.outerHTML);
console.log(renderTab({
cat: "Luna",
age: 2
}))