手写源码地址
mustache是最早的模板引擎库,底层实现机理为后续模板引擎的发展提供了崭新的思路
var templateStr2 = `
{{#fruits}}
- {{.}}
{{/fruits}}
`
var data2 = {
fruits: ['apple', 'strawberry', 'banana', 'pear']
}
var domStr2 = Mustache.render(templateStr2, data2);
list5.innerHTML = domStr2;
2.复杂数据循环
var list3 = document.getElementById('mustacheLoop');
var templateStr = `
{{#arr}}
-
{{name}}的个人信息
姓名:{{name}}
年龄:{{age}}
性别:{{sex}}
{{/arr}}
`;
var data = {
arr : [{
'name': 'Xiaoming',
'age': 12,
'sex': 'man'
}, {
'name': 'Xiaohong',
'age': 14,
'sex': 'female'
}, {
'name': 'Xiaoqiang',
'age': 16,
'sex': 'man'
}]
};
var domStr = Mustache.render(templateStr, data);
list3.innerHTML = domStr;
3.数组嵌套
var templateStr3 = `
{{#arr}}
-
{{name}}的个人信息
姓名:{{name}}
年龄:{{age}}
性别:{{sex}}
爱好:
{{#hobbits}}
- {{.}}
-
{{/hobbits}}
{{/arr}}
`
var data3 = {
arr: [{
'name': 'Xiaoming',
'age': 12,
'sex': 'man',
hobbits: ['singing', 'dancing', 'riding']
}, {
'name': 'Xiaohong',
'age': 14,
'sex': 'female',
hobbits: ['play game', 'painting', 'reading']
}, {
'name': 'Xiaoqiang',
'age': 16,
'sex': 'man',
hobbits: ['writing', 'cooking', 'shopping']
}]
};
var domStr3 = Mustache.render(templateStr3, data3);
list6.innerHTML = domStr3;
4.非循环
var list4 = document.getElementById('mustacheNoLoop');
var templateStr1 = `
this is {{type}} {{method}}
`;
var data1 = {
type: 'no loop',
method: 'mustache'
}
var domStr1 = Mustache.render(templateStr1, data1);
list4.innerHTML = domStr1
布尔值
//布尔值
var templateStr4 = `
{{#show}}
{{showMessage}}
{{/show}}
{{#hidden}}
{{hideMessage}}
{{/hidden}}
`;
var data4 = {
show: true,
hidden: false,
showMessage: 'show is true',
hideMessage: 'hidden is false'
};
var domStr4 = Mustache.render(templateStr4, data4);
list7.innerHTML = domStr4;
mustache的底层核心机理
最简单的模板引擎实现机理
利用正则表达式中的replace()方法,匹配进行替换
let temp = ' today is {{year}}-{{month}}-{{day}}
';
let da = {
year: new Date().getFullYear(),
month: new Date().getMonth() + 1,
day: new Date().getDate()
};
function render(template, data) {
return template.replace(/\{\{(\w+)\}\}/g, function(findstr, $1) {
return data[$1];
});
}
let res = render(temp, da);
console.log(res);
tokens
- JS的嵌套数组,即模板字符串的JS表示
手写mustache库