高级前端
手写代码
【Q660】实现一个 render/template 函数,可以用以渲染模板

实现一个 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 in a new tab)handlebars.js (opens in a new tab)

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

Author 回答者: shfshanyue (opens in a new tab)

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

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);
  });
}

Author 回答者: heretic-G (opens in a new tab)

function render(template, data) {
  return template.replace(/({{).*?(}})/g, function (...args) {
    return Function(`return this.${args[0].slice(2, -2).trim()}`).call(data);
  });
}

Author 回答者: haotie1990 (opens in a new tab)

function template(input, data) {
  const regex = RegExp(/\{\{([\w|\.|\[|\]|"]+)\}\}/, "g");
  let result;
  while ((result = regex.exec(input)) !== null) {
    // input字符串不能修改
    const [pattern, key] = result;
    // 由于改变了原字符串,但regex.lastIndex并未被重置,仍然从此位置开始匹配
    input = input.replace(pattern, eval(`data.${key}`));
    regex.lastIndex = 0; // 重置lastIndex;
  }
  return input;
}

Author 回答者: sunwenlong1995 (opens in a new tab)

const render = function(template,data){ return template.replace(/{{(.*?)}}/g,($0,$1) => eval('data.' + $1)) }