I'm not trying to reinvent the wheel here, just playing around with a question that was put to me. How would I write a simple template engine function. My immediate answer was more old school but with ES6 and the new spread operator, got me thinking maybe there is a better way of doing this now using the spread operator. Anyone got any ides ? Or would I still have to loop through and find my delimiter like i was using below const delimiter = '{{ name }}';.
const root = document.getElementById('root');
const html = "<p>My name is {{ name }}</p>";
var template = function(html){
return function(data){
for(var prop in data){
var regx = "{{\\s?" + prop + "\\s?}}";
html = html.replace(new RegExp(regx, "ig"), data[prop]);
}
return html;
}
}
var tmp = template(html);
root.innerHTML = tmp({
name: "John Doe"
});;