Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 template literals based on template variable [duplicate]

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 ?

like image 749
Guillaume Vincent Avatar asked Jul 28 '16 10:07

Guillaume Vincent


2 Answers

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/
like image 194
Alik Avatar answered Nov 19 '22 20:11

Alik


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.

like image 24
Estus Flask Avatar answered Nov 19 '22 19:11

Estus Flask