mustache模版引擎
什么是模板引擎
将数据变为视图的解决方案
- 使用DOM:笨拙
- 数组join法: 曾经
- es6的反引号法:ES6中新增的’${a}`很好用
- 模板引擎:解决数据变为视图的方法
使用DOM
数组join
Es6的反引号法
mustache基本使用
Mustache.render(templateStr, data)(模板字符串,数据)
mustache库机理
什么是tokens
- tokens是一个JS的嵌套数组,就是模板字符串的js表示
- 它是 ‘抽象语法树’ ‘虚拟节点’ 等的开山鼻祖
<h1>我买了一个{{thing}},好{{mood}}啊</h1>
tokens
当模板字符串中有循环存在时,它将被编译为嵌套更深的tokens
手写实现mustache
function mustacheRender(template, data) {
// 将模板中的{{}}替换为变量占位符
const regex = /\{\{(.+?)\}\}/g;
template = template.replace(regex, function(match, key) {
// 使用"."进行属性路径解析
let value = data;
key.split('.').forEach(prop => {
if (value && typeof value === 'object') {
value = value[prop];
} else {
// 如果路径中某个属性不存在,则返回空字符串
value = '';
}
});
return value !== undefined ? value : '';
});
return template;
}
// 示例用法:
const template = "Hello, {{name}}! You are {{age}} years old.";
const data = { name: 'John Doe', age: 30 };
console.log(mustacheRender(template, data)); // 输出:"Hello, John Doe! You are 30 years old."