I am working on an Express.js project where I need to replace placeholders in an HTML file with data from a JSON file. However, I want the HTML file to look like an actual page instead of having placeholders with weird texts (like {{username}}). Currently, I am using a custom attribute in the HTML, and my replacement logic looks like this:
HTML Input:
<td data-key="invoice.productDetails.serialNumber.value">1</td>
Replacement Logic (Express.js):
document.querySelectorAll('[data-key]').forEach((element) => {
const key = element.getAttribute('data-key');
const newValueObj = jsonDataMap.get(key);
if (newValueObj) {
element.textContent = newValueObj.attributeValue;
}
});
This works for my proof of concept, but I am wondering if there are better solutions or best practices for this kind of task. Specifically:
Are there better ways to add demo names (like in a template engine) instead of placeholders and still achieve the same functionality?
Is it better to use a template engine for this purpose rather than custom attributes and manual replacement?
If anyone has faced a similar situation, how did you solve it?
I appreciate any insights or recommendations!
Arun Thomas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.