手写简单的模板引擎
Opened this issue · 0 comments
colinox commented
手写简单的模板引擎
单级对象数据获取
var data = {
name: 'ruoyu',
addr: 'Hunger Valley'
};
var tpl = 'Hello, my name is {{name}}. I am in {{addr}}.';
var reg=/{{([a-zA-Z_$][a-zA-Z0-9_.]*)}}/g;
var newStr = tpl.replace(reg,function(raw,key,offset,string){
return data[key]||raw;
})
多级对象数据获取
var data = {
name: 'ruoyu',
age: '17',
friend: {
name: 'hunger',
car: {
color: 'white'
}
}
}
var tpl = 'Hello, my name is {{name}}. I am in {{age}},I have a friend {{friend.name}},he has a {{friend.car.color}} car'
var reg = /{{([a-zA-Z_$][a-zA-Z0-9_.]*)}}/g;
var newStr = tpl.replace(reg, function (raw, key, offset, string) {
var paths = key.split('.');
var lookup = data;
while (paths.length > 0) {
lookup = lookup[paths.shift()];
}
return lookup || raw;
})