我尝试呈现一个ES6模板文字变量:
function render(template, data){
...
}
const template = 'resources/${id}/';
console.log(render(template, {id: 1})); // -> resources/1/
是否存在一种将带有上下文的字符串模板转换为使用ES6模板文字特性的格式化字符串的方法?
我尝试呈现一个ES6模板文字变量:
function render(template, data){
...
}
const template = 'resources/${id}/';
console.log(render(template, {id: 1})); // -> resources/1/
是否存在一种将带有上下文的字符串模板转换为使用ES6模板文字特性的格式化字符串的方法?
使用简单的模板字面量无法做到这一点。
但是,通过将您的字面量包装到函数中,您可以实现这样的行为。由于ES6的功能(解构和箭头函数),结果代码很简单
function render(template, data) {
return template(data);
}
const tpl = ({ id }) => `resources/${id}/`;
console.log(render(tpl, { id: 1})); // resources/1/
ES6模板字面量不能在运行时编译。要实现这一点,应使用第三方库,例如es6-template
。
目前使用模板字面量语法没有真正的好处,可以选择任何其他模板引擎来代替。
(({ id }) => `resources/${id}/`)({ id: 1})
- alex_1948511'resources/${id}/'
作为一个变量保存。 - user1663023\
resources/${id}/``被保存在一个从网络或文件读取的变量中,你会怎么做? - user1663023