I try to render a ES6 template literal variable :
function render(template, data){
...
}
const template = 'resources/${id}/';
console.log(render(template, {id: 1})); // -> resources/1/
Does exist a way to transform a string template with context into a formated string with ES6 template literals feature ?
You can not do this with simple template literals.
However, you can achieve such behaviour by wrapping your literals into functions. Thanks to ES6 features (desctructuring and arrow functions), the result code is simple
function render(template, data) {
return template(data);
}
const tpl = ({ id }) => `resources/${id}/`;
console.log(render(tpl, { id: 1})); // resources/1/
ES6 template literals can't be compiled at run time. To do this, third-party library should be used, like es6-template
.
At this point there's no real benefit in using template literal syntax, any other template engine of choice may be used instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With