You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
function render(template,context){
let reg = /\{\{\s*\w+(\.\w+)*\s*\}\}/g
return template.replace(reg,function(match){
return match.replace(/{|}/g,'').trim().split('.').reduce((prev,cur) => prev[cur],context)
})
}
let context = {
name:'lily',
age:18,
family:{
count:3
}
}
let template = '{{ name }}很name厉害,才{{age}}岁,家里有{{family.count}}口人'
let result = render(template,context)
console.log(result)
Activity
[-]前端进阶算法5:一看就懂的队列及配套算法题[/-][+]待录入[/+][-]待录入[/-][+]百度:模版渲染[/+]7777sea commentedon May 9, 2020
2384830985 commentedon May 9, 2020
onlyil commentedon May 9, 2020
luweiCN commentedon May 9, 2020
sisterAn commentedon May 10, 2020
解答:使用正则 + trim
/\{\{(.*?)\}\}/g匹配到到所有的{{name}},{{age}}str.replace(regexp|substr, newSubStr|function),其中第二个参数可以是fucntion (replacement),该函数的返回值将替换掉第一个参数匹配到的结果,将所有匹配到的字符替换成指定的字符String.prototype.trim()去除分隔符与变量之间空白字符详细解答可查看:一行代码实现一个简单的模板字符串替换
WJmascara commentedon May 12, 2020
function render(template, context) {
const rule = /{{(.*?)}}/g;
return template.replace(rule, function($, key) {
const arr = key.trim().split('.');
return arr.reduce((cal, item) => {
return cal[item];
}, context);
});
}
zjhlaap commentedon Jul 10, 2020
mugongxu commentedon Aug 6, 2020
caitlinChang commentedon Sep 5, 2020
xllpiupiu commentedon Oct 2, 2021
AirKK commentedon Apr 7, 2022
kangkang123269 commentedon Feb 23, 2023
续楼上另一直处理方法