<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>template模板</title>
</head>
<body>
<a href=""></a>
<script type="text/javascript">
// 写一个方法第一个参数输入模板(占位或者怎么搞)、第二个输入数据
let template = `<div><p>姓名:{{b.a.name}} 年龄:{{b.a.age}}</p><p class="information_now">座右铭:{{a}}</p></div>`,
template1 = `<div><p>姓名:{{b.a.name}} 年龄:{{b.a.age}}</p><p class="information_now">座右铭:<a href="{{b.a.src}}">点击地址进行关注!</a></p></div> `;
var a = 'hello world',
b = {
a: {
name: '我是测试的全局变量',
age: "你猜"
}
};
/**
* 模板语言
* @param {[string]} str [字符串模板]
* @param {[object]} obj [模板对应的数据/如果不存在则取全局变量]
* @return {[string]} [dom字符串]
*/
const achieveTemplate = (str, obj) => {
var result, reg = /{{([\w.]+)}}/i,
pj = typeof obj == 'object' ? '${obj.' : '${';
//定义正则检索字符串匹配含双大括号的内容,\w:匹配字符,+:匹配至少一个字符,():多次匹配
while ((result = reg.exec(str)) != null) str = str.replace(result[0], pj + [result[1]] + "}");
return eval("`" + str + "`");
};
// 当{{变量}}变量从全局环境拿
document.body.innerHTML += achieveTemplate(template);
// 当变量从自己的参数里拿
document.body.innerHTML += achieveTemplate(template1, {
a: '来个关注好不好啊!',
b: {
a: {
name: '听闻青春',
age: 18,
src: 'https://blog.csdn.net/qq_21423689'
}
}
});
</script>
</body>
</html>
效果:
请使用cv大法进行查看!