【问题标题】:ES6 template literals based on template variable [duplicate]基于模板变量的ES6模板文字[重复]
【发布时间】:2016-12-02 16:22:17
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript ecmascript-6 template-literals


    【解决方案1】:

    你不能用简单的模板文字做到这一点。

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

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

    【讨论】:

    • 或者更简单:(({ id }) => `resources/${id}/`)({ id: 1})
    • 但这并不能回答原始问题。原始问题的寓意是您持有的是 'resources/${id}/' 作为变量。
    • @QianChen 你为什么这么认为?我相信我已经说得很清楚了。
    • 如果`resources/${id}/` 保存在从网络或文件读取的变量中,你会怎么做?
    • @QianChen 我不明白。我为什么要为此做点什么?
    【解决方案2】:

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

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

    【讨论】:

    • 这仍然相关吗?我面临同样的问题,想知道是否使用 es6 文字模板
    • 是的。需要时使用模板引擎。
    猜你喜欢
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 2019-11-17
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    相关资源
    最近更新 更多