# 实现一个 render/template 函数,可以用以渲染模板
更多描述
const template = '{{ user["name"] }},今天你又学习了吗 - 用户ID: {{ user.id }}';
const data = {
user: {
id: 10086,
name: "山月",
},
};
//=> "山月,今天你又学习了吗 - 用户ID: 10086"
render(template, data);
注意:
- 注意深层嵌套数据
- 注意
user['name']
属性
关于复杂的模板编译解析执行,可参考 mustache (opens new window) 与 handlebars.js (opens new window) :::
Issue
欢迎在 Gtihub Issue 中回答此问题: Issue 678 (opens new window)
Author
代码可见 实现一个 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);
});
}