模板引擎mustache学习之Scanner扫描器(三)

83 阅读1分钟

现在的文件目录如下:

I@13RHP{D56MZLQ3K~OXB)K.png

Scanner.js

export default class Scanner {
  constructor(templateStr) {
    this.tempStr = templateStr; // 源文本数据
    this.tail = templateStr; // 此文本长度会随着扫描器一直在缩减
    this.pos = 0; // 记录当前扫描到哪个位置
  }

  // 扫描器 通过此函数扫描出来 指定标识如{{ || }} 之前 之间 之后的内容
  scannUtil(tag) {
    const start = this.pos; // 保存一下当前开始的索引位置

    // 如果tail一直是有内容 并且 没有碰到tag标识那么一直扫描
    while (!this.eos() && this.tail.indexOf(tag) !== 0) {
      this.pos++;
      this.tail = this.tempStr.substring(this.pos);
    }

    return this.tempStr.substring(start, this.pos);
  }

  // 此函数用来跳过指定标识
  scann(tag) {
    // 跳转首先我们要确保当前位置位置是{{ || }}
    if (this.tail.indexOf(tag) === 0) {
      this.pos += tag.length; // 并把pos往后推几位
      this.tail = this.tempStr.substring(this.pos);
    }
  }

  eos() {
    return this.tail === ""; // 如果tail为空说明到了结尾位置了!
  }
}

index.js

import Scanner from "./Scanner";
window.Mustache = {
  render(tempStr, data) {
    const scanner = new Scanner(tempStr); // 实例化Scanner类

    let words = "";

    while (!scanner.eos()) {
      words = scanner.scannUtil("{{");
      console.log(words); // 这里自己可以输出在控制台看一下
      // 跳过指定位置
      scanner.scann("{{");

      // 把{{处理好了 但是我们好像还没有处理如果是}}对不对?那么这就很简单了!
      words = scanner.scannUtil("}}");
      console.log(words); // 这里自己可以输出在控制台看一下
      // 跳过指定位置
      scanner.scann("}}");
    }
  },
};

其它的文件未发生变化的在此不做展示, 如果想要了解请看之前的文章内容哈!