<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>String</title>
</head>
<body>
<script>
/**
*自定义模板引擎的实现
*注意
* 1.一个字符串中可以有多个需要渲染的模板字符串,所以需要用到递归
*步骤
* 1.定义模板语法{{}}
* 正则:
* /\{\{(\w+)\}\}/ 匹配{{}}区域
* exec()(https://blog.csdn.net/weixin_38659265/article/details/109307686中有exec()相关介绍)
* replace(regexp/substr,replacement)在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串
* 2.实现渲染函数
* 从左至右,匹配模板字符串
* 匹配到:用数据中对应变量值替换对应字符串,使用递归直至没有模板字符串
* 匹配不到:直接返回模板
*/
let template = '我是{{name}},年龄{{age}},性别{{sex}}';
let data = {
name: '张三',
age: 18
}
console.log(render(template, data)); // 我是姓名,年龄18,性别undefined
function render(template, data) {
const reg = /\{\{(\w+)\}\}/; // 模板字符串正则
if (reg.test(template)) { // 判断模板⾥是否有模板字符串
const name = reg.exec(template)[1]; // 查找当前模板⾥第⼀个模板字符串的字段
template = template.replace(reg, data[name]); // 将第⼀个模板字符串渲染
return render(template, data); // 递归的渲染并返回渲染后的结构
}
return template; // 如果模板没有模板字符串直接返回
}
</script>
</body>
</html>