1、首先要拆分格式
原理: 逐级拆分,scanUntil用于移动指针,一直移动到指定的"{{"字符,将指针移动的字符用word记录下来,找到“{{”后用scan将字符跳过,不截取"{{"这个字符的内容,将字符的长度赋值给指针,使指针移动后两位,继续采用scanUntil进行截取,然后再找到"}}"字符,跳过这个字符如此循环。
2、上代码
Scanner.js
// 扫描器
export default class Scanner{
constructor(template){
// 指针
this.pop = 0
// 尾巴
this.tail = template
// 模板
this.templateStr = template
}
scan(tag){
while(this.tail.indexOf(tag)===0){
// 跳过指针
this.pop+=tag.length
// 改变尾巴
this.tail =this.templateStr.substr(this.pop)
}
}
// 用于获取字符
scanUtil(endTag){
// 记录指针截取开始的位置
var indexStart = this.pop
// 如果结束的标签没找到
while(this.tail.indexOf(endTag)!=0 && !this.eoc()){
// 指针继续往下移
this.pop++;
// 尾巴变化
this.tail =this.templateStr.substr(this.pop)
}
// 截取指针开始到移动后的位置
return this.templateStr.substring(indexStart,this.pop)
}
// 不准指针超出字符长度
eoc(){
return this.pop >= this.templateStr.length;
}
}
index.js
import Scanner from './Scanner.js'
window.SSG_TemplateEngine = {
render(template,data){
var scanner = new Scanner(template)
var word;
while(!scanner.eoc()){
word = scanner.scanUtil("{{")
console.log(word)
scanner.scan('{{')
word = scanner.scanUtil("}}")
scanner.scan('}}')
console.log(word)
}
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>世界你好啊</h1>
<script src="/xuni/bundle.js"></script>
</body>
<script>
var template =`<div>世界你好{{thing}}</div>`
SSG_TemplateEngine.render(template,{})
</script>
</html>