Don't repeat yourself. It's one of the golden rules for good code. for some reason when writing HTML it's almost completely ignored, especially by new devs who try to hardcode everything.
[This example uses bootstrap 4 for the table, but it is not necessary to use bootstrap for templates]
What you need to use is the <template></template>
tag.
Lets say you have a simple program, printing numbers in a range. You can see the layout of the finished page on github, using index.html (example code below)
function displayData(start, end) {
let result = ""
for (let i = start; i <= end; i++) {
result += ` ${i}`;
}
document.getElementById("result").innerHTML = result;
}
You can easily do this as I've done above with a string concatenation, but its not impressive. Since you don't know how many numbers you'll need, you couldn't hardcode a table.... or can you?
Lets add a template element to our HTML page, it can go anywhere, but it should look a bit like
<template id="dataTemplate">
<tr>
<td id="col1"></td>
<td id="col2"></td>
<td id="col3"></td>
<td id="col4"></td>
<td id="col5"></td>
</tr>
</template>
This template is for a table, elsewhere in the HTML I have the body set up.
<table class="table table-striped" id="resultTable">
<thead class="thead-dark">
<tr>
<th colspan="5">Results</th>
</tr>
</thead>
<tbody id="resultsBody">
</tbody>
</table>
I then link these elements together in the javascript:
const template = document.getElementById("dataTemplate");
const resultsBody=document.getElementById("resultsBody")
resultsBody.innerHTML = ""
Now in our loop, we setup a datarow constant, and add each element into the textcontent as we loop. Then appending the new datarow as a child to the resultsBody, also incrementing by 5 every loop, since we're adding elements 5 at a time.
for (let i = start; i <= end; i+=5) {
const datarow = document.importNode(template.content, true);
datarow.getElementById("col1").textContent = i;
datarow.getElementById("col2").textContent = i+1;
datarow.getElementById("col3").textContent = i+2;
datarow.getElementById("col4").textContent = i+3;
datarow.getElementById("col5").textContent = i+4;
resultsBody.appendChild(datarow)
}
Now you can put inputs for 1 through 100 and get 20 rows of numbers!
Templates done easily with only vanilla JS. No complicated frontend frameworks needed.
This example does have some problems, if you aren't working in multiples of 5 you'll end up with extra numbers. Hopefully its showed you that templates are super easy to use.
Top comments (1)
This is a good explanation of how to use template tags and the DRY Principle, thanks.