Answer the question
In order to leave comments, you need to log in
What is the best way to implement value substitution in template.content?
I decided to try a new template tag for myself, but I don’t understand how best to insert data into the template?
In addition, my version does not allow you to set tag attributes, but these are already trifles.
table to which rows with data are added
<table id="tbl">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody></tbody>
</table>
<template id="tpl">
<tr>
<td var="name"></td>
<td var="age"></td>
</tr>
</template>
const rows = [
{name: 'Anton', age: 30},
{name: 'Ivan', age: 20}
];
const tpl = document.getElementById('tpl').content;
const tbl = document.querySelector('#tbl tbody');
rows.forEach(function (row) {
let tplClone = tpl.cloneNode(true);
tplClone.querySelectorAll('[var]').forEach(function (el) {
el.innerHTML = row[el.getAttribute('var')] || '';
el.removeAttribute('var');
});
tbl.appendChild(tplClone);
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question