基于模板变量的ES6模板文字

时间:2016-07-28 10:21:01

标签: javascript ecmascript-6 template-literals

我尝试渲染ES6模板文字变量:

function render(template, data){
 ...
}
const template = 'resources/${id}/';
console.log(render(template, {id: 1})); // -> resources/1/

是否存在将带有上下文的字符串模板转换为具有ES6模板文字功能的格式化字符串的方法?

2 个答案:

答案 0 :(得分:12)

使用简单的模板文字无法做到这一点。

但是,您可以通过将文字包装到函数中来实现此类行为。由于ES6功能(解构和箭头功能),结果代码很简单

function render(template, data) {
  return template(data);
}
const tpl = ({ id }) => `resources/${id}/`;

console.log(render(tpl, { id: 1})); // resources/1/

答案 1 :(得分:0)

ES6模板文字无法在运行时编译。为此,应使用第三方库,如es6-template

此时,使用模板文字语法没有任何实际好处,可以使用任何其他选择的模板引擎。

相关问题