qappleh / Interview

我是追梦赤子心,公众号「深圳湾码农」的作者,某上市集团公司高级前端开发,深耕前端领域多年,每天攻破一道题,带你从0到1系统构建web全栈完整的知识体系!
https://github.com/qappleh/Interview
1.14k stars 95 forks source link

Day385:实现一个简易的模板引擎?(阿里) #388

Open qappleh opened 3 years ago

qappleh commented 3 years ago

示例:

const template = '嗨,{{ info.name.value }}您好,今天是星期 {{ day.value }}';

const data = {
  info: {
    name: {
      value: '张三'
    }
  },
  day: {
    value: '三'
  }
};

render(template, data); // 嗨,张三您好,今天是星期三
btea commented 3 years ago
function render(template, data) {
    return template.replace(/\{\{([\s\S]+?)\}\}/g, function(match, $1) {
        var val = $1.trim();
        return eval('data.' + val)
    })
}