基于模板变量的ES6模板文字 [英] ES6 template literals based on template variable

查看:127
本文介绍了基于模板变量的ES6模板文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试呈现ES6模板文字变量:

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/

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

推荐答案

您不能使用简单的模板文字来做到这一点.

You can not do this with simple template literals.

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

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/

这篇关于基于模板变量的ES6模板文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆