Open shfshanyue opened 3 years ago
代码可见 实现一个 render/template 函数,可以用以渲染模板 - codepen
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)
})
}
function render (template, data) {
return template.replace(/({{).*?(}})/g, function (...args) {
return Function(`return this.${args[0].slice(2, -2).trim()}`).call(data)
})
}
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;
}
const render = function(template,data){ return template.replace(/{{(.*?)}}/g,($0,$1) => eval('data.' + $1)) }
注意:
user['name']
属性