Mustache底层实现原理2

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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值