极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。
山月训练营之面试直通车 服务上线了,从准备简历、八股文准备、项目经历准备、面试、面经、面经解答、主观问题答复、谈薪再到入职的一条龙服务。

# 实现一个 render/template 函数,可以用以渲染模板

更多描述

const template = '{{ user["name"] }},今天你又学习了吗 - 用户ID: {{ user.id }}';

const data = {
  user: {
    id: 10086,
    name: "山月",
  },
};

//=> "山月,今天你又学习了吗 - 用户ID: 10086"
render(template, data);

注意:

  1. 注意深层嵌套数据
  2. 注意 user['name'] 属性

关于复杂的模板编译解析执行,可参考 mustache (opens new window)handlebars.js (opens new window) :::

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 678 (opens new window)

代码可见 实现一个 render/template 函数,可以用以渲染模板 - codepen (opens new window)

function get(source, path, defaultValue = undefined) {
  // a[3].b -> a.3.b -> [a, 3, b]
  const paths = path
    .replace(/\[(\w+)\]/g, ".$1")
    .replace(/\["(\w+)"\]/g, ".$1")
    .replace(/\['(\w+)'\]/g, ".$1")
    .split(".");
  let result = source;
  for (const p of paths) {
    result = result?.[p];
  }
  return result === undefined ? defaultValue : result;
}

function render(template, data) {
  return template.replace(/{{\s+([^\s]+)\s+}}/g, (capture, key) => {
    return get(data, key);
  });
}
Last Updated: 11/14/2022, 1:11:14 PM