作家
登录

如何实现一个基于DOM的模板引擎

作者: 来源: 2017-08-14 09:13:04 阅读 我要评论

若何实现一个基于DOM的模板引擎

题图:Vincent Guth

注:本文所有代码均可在本人的小我项目colon中找到,本文也同步到了知乎专栏

可能你已经领会到了 Vue 所带来的便捷了,信赖有一部分原因也是因为其基于 DOM 的语法简洁的模板衬着引擎。这篇文┞仿将会介绍若何实现一个基于 DOM 的模板引擎(就像 Vue 的模板引擎一样)。

Preface

开端之前,我们先来看一下最终的效不雅:

  1. const compiled = Compile(`<h1>Hey 🌰, {{ greeting }}</h1>`, { 
  2.     greeting: `Hello World`, 
  3. }); 
  4. compiled.view // => `<h1>Hey 🌰, Hello World</h1>`  

Compile

实现一个模板引擎实际上就是实现一个编译器,就像如许:

  1. const compiled = Compile(template: String|Node, data: Object); 
  2.  
  3. compiled.view // => compiled template  

起首,让我们来看下 Compile 内部是若何实现的:

  1. // compile.js 
  2. /** 
  3.  * template compiler 
  4.  * 
  5.  * @param {String|Node} template 
  6.  * @param {Object} data 
  7.  */ 
  8. function Compile(template, data) { 
  9.     if (!(this instanceof Compile)) return new Compile(template, data); 
  10.  
  11.     this.options = {}; 
  12.     this.data = data; 
  13.  
  14.     if (template instanceof Node) { 
  15.         this.options.template = template; 
  16.     } else if (typeof template === 'string') { 
  17.         this.options.template = domify(template); 
  18.     } else { 
  19.         console.error(`"template" only accept DOM node or string template`); 
  20.     } 
  21.  
  22.     template = this.options.template; 
  23.  
  24.     walk(template, (node, next) => { 
  25.         if (node.nodeType === 1) { 
  26.             // compile element node 
  27.             this.compile.elementNodes.call(this, node); 
  28.             return next(); 
  29.         } else if (node.nodeType === 3) { 
  30.             // compile text node 
     1/10    1 2 3 4 5 6 下一页 尾页

      推荐阅读

      雷军开造空调正面挑战董明珠?小米说只是生态链

    曾经和格力电器董事长董明珠有10亿赌约的小米,要做空调了? 8月10日,小米智能硬件生态链企业智米科技宣布了一款售价4399元的全直流变频空调,但品牌不是&ldquo;小米&rdqu>>>详细阅读


    本文标题:如何实现一个基于DOM的模板引擎

    地址:http://www.17bianji.com/lsqh/36664.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)