Convert a string to a template string

前端 未结 19 2422
轮回少年
轮回少年 2020-11-22 08:30

Is it possible to create a template string as a usual string

let a=\"b:${b}\";

an then convert it into a template string

le         


        
19条回答
  •  深忆病人
    2020-11-22 09:22

    Still dynamic but seems more controlled than just using a naked eval:

    const vm = require('vm')
    const moment = require('moment')
    
    
    let template = '### ${context.hours_worked[0].value} \n Hours worked \n #### ${Math.abs(context.hours_worked_avg_diff[0].value)}% ${fns.gt0(context.hours_worked_avg_diff[0].value, "more", "less")} than usual on ${fns.getDOW(new Date())}'
    let context = {
      hours_worked:[{value:10}],
      hours_worked_avg_diff:[{value:10}],
    
    }
    
    
    function getDOW(now) {
      return moment(now).locale('es').format('ffffdd')
    }
    
    function gt0(_in, tVal, fVal) {
      return _in >0 ? tVal: fVal
    }
    
    
    
    function templateIt(context, template) {
      const script = new vm.Script('`'+template+'`')
      return script.runInNewContext({context, fns:{getDOW, gt0 }})
    }
    
    console.log(templateIt(context, template))
    

    https://repl.it/IdVt/3

提交回复
热议问题