问题
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 ?
回答1:
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/
回答2:
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.
来源:https://stackoverflow.com/questions/38633594/es6-template-literals-based-on-template-variable