ES6 template literals based on template variable [duplicate]

一个人想着一个人 提交于 2020-01-13 10:02:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!