成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

如何實現一個基于DOM的模板引擎

開發 前端
可能你已經體會到了 Vue 所帶來的便捷了,相信有一部分原因也是因為其基于 DOM 的語法簡潔的模板渲染引擎。這篇文章將會介紹如何實現一個基于 DOM 的模板引擎(就像 Vue 的模板引擎一樣)。

[[199802]]

題圖: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 
  31.             this.compile.textNodes.call(this, node); 
  32.         } 
  33.         next(); 
  34.     }); 
  35.  
  36.     this.view = template; 
  37.     template = null
  38.  
  39. Compile.compile = {};  

walk

通過上面的代碼,可以看到 Compile 的構造函數主要就是做了一件事 ———— 遍歷 template,然后通過判斷節點類型的不同來做不同的編譯操作,這里就不介紹如何遍歷 template 了,不明白的話可以直接看 walk 函數的源碼,我們著重來看下如何編譯這些不同類型的節點,以編譯 node.nodeType === 1 的元素節點為例:

  1. /** 
  2.  * compile element node 
  3.  * 
  4.  * @param {Node} node 
  5.  */ 
  6. Compile.compile.elementNodes = function (node) { 
  7.     const bindSymbol = `:`; 
  8.     let attributes = [].slice.call(node.attributes), 
  9.         attrName = ``, 
  10.         attrValue = ``, 
  11.         directiveName = ``; 
  12.  
  13.     attributes.map(attribute => { 
  14.         attrName = attribute.name
  15.         attrValue = attribute.value.trim(); 
  16.  
  17.         if (attrName.indexOf(bindSymbol) === 0 && attrValue !== '') { 
  18.             directiveName = attrName.slice(bindSymbol.length); 
  19.  
  20.             this.bindDirective({ 
  21.                 node, 
  22.                 expression: attrValue, 
  23.                 name: directiveName, 
  24.             }); 
  25.             node.removeAttribute(attrName); 
  26.         } else { 
  27.             this.bindAttribute(node, attribute); 
  28.         } 
  29.     }); 
  30. };  

噢忘記說了,這里我參考了 Vue 的指令語法,就是在帶有冒號 : 的屬性名中(當然這里也可以是任何其他你所喜歡的符號),可以直接寫 JavaScript 的表達式,然后也會提供幾個特殊的指令,例如 :text, :show 等等來對元素做一些不同的操作。

其實該函數只做了兩件事:

  • 遍歷該節點的所有屬性,通過判斷屬性類型的不同來做不同的操作,判斷的標準就是屬性名是否是冒號 : 開頭并且屬性的值不為空;
  • 綁定相應的指令去更新屬性。

Directive

其次,再看一下 Directive 內部是如何實現的:

  1. import directives from './directives'
  2. import { generate } from './compile/generate'
  3.  
  4. export default function Directive(options = {}) { 
  5.     Object.assign(this, options); 
  6.     Object.assign(this, directives[this.name]); 
  7.     this.beforeUpdate && this.beforeUpdate(); 
  8.     this.update && this.update(generate(this.expression)(this.compile.options.data)); 
  9.  

Directive 做了三件事:

  • 注冊指令(Object.assign(this, directives[this.name]));
  • 計算指令表達式的實際值(generate(this.expression)(this.compile.options.data));
  • 把計算出來的實際值更新到 DOM 上面(this.update())。

在介紹指令之前,先看一下它的用法:

  1. Compile.prototype.bindDirective = function (options) { 
  2.     new Directive({ 
  3.         ...options, 
  4.         compile: this, 
  5.     }); 
  6. }; 
  7.  
  8. Compile.prototype.bindAttribute = function (node, attribute) { 
  9.     if (!hasInterpolation(attribute.value) || attribute.value.trim() == ''return false
  10.  
  11.     this.bindDirective({ 
  12.         node, 
  13.         name'attribute'
  14.         expression: parse.text(attribute.value), 
  15.         attrName: attribute.name
  16.     }); 
  17. };  

bindDirective 對 Directive 做了一個非常簡單的封裝,接受三個必填屬性:

  • node: 當前所編譯的節點,在 Directive 的 update 方法中用來更新當前節點;
  • name: 當前所綁定的指令名稱,用來區分具體使用哪個指令更新器來更新視圖;
  • expression: parse 之后的 JavaScript 的表達式。

updater

在 Directive 內部我們通過 Object.assign(this, directives[this.name]); 來注冊不同的指令,所以變量 directives 的值可能是這樣的:

  1. // directives 
  2. export default { 
  3.     // directive `:show` 
  4.     show: { 
  5.         beforeUpdate() {}, 
  6.         update(show) { 
  7.             this.node.style.display = show ? `block` : `none`; 
  8.         }, 
  9.     }, 
  10.     // directive `:text` 
  11.     text: { 
  12.         beforeUpdate() {}, 
  13.         update(value) { 
  14.             // ... 
  15.         }, 
  16.     }, 
  17. };  

所以假設某個指令的名字是 show 的話,那么 Object.assign(this, directives[this.name]); 就等同于:

  1. Object.assign(this, { 
  2.     beforeUpdate() {}, 
  3.     update(show) { 
  4.         this.node.style.display = show ? `block` : `none`; 
  5.     }, 
  6. });  

表示對于指令 show,指令更新器會改變該元素 style 的 display 值,從而實現對應的功能。所以你會發現,整個編譯器結構設計好后,如果我們要拓展功能的話,只需簡單地編寫指令的更新器即可,這里再以指令 text 舉個例子:

  1. // directives 
  2. export default { 
  3.     // directive `:show` 
  4.     // show: { ... }, 
  5.     // directive `:text` 
  6.     text: { 
  7.         update(value) { 
  8.             this.node.textContent = value; 
  9.         }, 
  10.     }, 
  11. };  

有沒有發現編寫一個指令其實非常的簡單,然后我們就可以這么使用我們的 text 指令了:

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

generate

講到這里,其實還有一個非常重要的點沒有提到,就是我們如何把 data 真實數據渲染到模板中,比如 <h1>Hey 🌰, {{ greeting }}</h1> 如何渲染成 <h1>Hey 🌰, Hello World</h1>,通過下面三個步驟即可計算出表達式的真實數據:

  • 把 <h1>Hey 🌰, {{ greeting }}</h1> 解析成 'Hey 🌰, ' + greeting 這樣的 JavaScript 表達式;
  • 提取其中的依賴變量并取得所在 data 中的對應值;
  • 利用 new Function() 來創建一個匿名函數來返回這個表達式;
  • ***通過調用這個匿名函數來返回最終計算出來的數據并通過指令的 update 方法更新到視圖中。

parse text

  1. // reference: https://github.com/vuejs/vue/blob/dev/src/compiler/parser/text-parser.js#L15-L41 
  2. const tagRE = /\{\{((?:.|\n)+?)\}\}/g; 
  3. function parse(text) { 
  4.     if (!tagRE.test(text)) return JSON.stringify(text); 
  5.  
  6.     const tokens = []; 
  7.     let lastIndex = tagRE.lastIndex = 0; 
  8.     let index, matched; 
  9.  
  10.     while (matched = tagRE.exec(text)) { 
  11.         index = matched.index
  12.         if (index > lastIndex) { 
  13.             tokens.push(JSON.stringify(text.slice(lastIndex, index))); 
  14.         } 
  15.         tokens.push(matched[1].trim()); 
  16.         lastIndex = index + matched[0].length; 
  17.     } 
  18.  
  19.     if (lastIndex < text.length) tokens.push(JSON.stringify(text.slice(lastIndex))); 
  20.  
  21.     return tokens.join('+'); 
  22.  

該函數我是直接參考 Vue 的實現,它會把含有雙花括號的字符串解析成標準的 JavaScript 表達式,例如:

  1. parse(`Hi {{ user.name }}, {{ colon }} is awesome.`); 
  2. // => 'Hi ' + user.name + ', ' + colon + ' is awesome.'  

extract dependency

我們會通過下面這個函數來提取出一個表達式中可能存在的變量:

  1. const dependencyRE = /"[^"]*"|'[^']*'|\.\w*[a-zA-Z$_]\w*|\w*[a-zA-Z$_]\w*:|(\w*[a-zA-Z$_]\w*)/g; 
  2. const globals = [ 
  3.     'true''false''undefined''null''NaN''isNaN''typeof''in'
  4.     'decodeURI''decodeURIComponent''encodeURI''encodeURIComponent''unescape'
  5.     'escape''eval''isFinite''Number''String''parseFloat''parseInt'
  6. ]; 
  7.  
  8. function extractDependencies(expression) { 
  9.     const dependencies = []; 
  10.  
  11.     expression.replace(dependencyRE, (match, dependency) => { 
  12.         if ( 
  13.             dependency !== undefined && 
  14.             dependencies.indexOf(dependency) === -1 && 
  15.             globals.indexOf(dependency) === -1 
  16.         ) { 
  17.             dependencies.push(dependency); 
  18.         } 
  19.     }); 
  20.  
  21.     return dependencies; 
  22.  

通過正則表達式 dependencyRE 匹配出可能的變量依賴后,還要進行一些對比,比如是否是全局變量等等。效果如下:

  1. extractDependencies(`typeof String(name) === 'string'  && 'Hello ' + world + '! ' + hello.split('').join('') + '.'`); 
  2. // => ["name""world""hello" 

這正是我們需要的結果,typeof, String, split 和 join 并不是 data 中所依賴的變量,所以不需要被提取出來。

generate

  1. export function generate(expression) { 
  2.     const dependencies = extractDependencies(expression); 
  3.     let dependenciesCode = ''
  4.  
  5.     dependencies.map(dependency => dependenciesCode += `var ${dependency} = this.get("${dependency}"); `); 
  6.  
  7.     return new Function(`data`, `${dependenciesCode}return ${expression};`); 
  8.  

我們提取變量的目的就是為了在 generate 函數中生成相應的變量賦值的字符串便于在 generate 函數中使用,例如:

  1. new Function(`data`, ` 
  2.     var name = data["name"]; 
  3.     var world = data["world"]; 
  4.     var hello = data["hello"]; 
  5.     return typeof String(name) === 'string'  && 'Hello ' + world + '! ' + hello.split('').join('') + '.'
  6. `); 
  7.  
  8. // will generated: 
  9.  
  10. function anonymous(data) { 
  11.     var name = data["name"]; 
  12.     var world = data["world"]; 
  13.     var hello = data["hello"]; 
  14.     return typeof String(name) === 'string'  && 'Hello ' + world + '! ' + hello.split('').join('') + '.'
  15.  

這樣的話,只需要在調用這個匿名函數的時候傳入對應的 data 即可獲得我們想要的結果了。現在回過頭來看之前的 Directive 部分代碼應該就一目了然了:

  1. export default class Directive { 
  2.     constructor(options = {}) { 
  3.         // ... 
  4.         this.beforeUpdate && this.beforeUpdate(); 
  5.         this.update && this.update(generate(this.expression)(this.compile.data)); 
  6.     } 
  7.  

generate(this.expression)(this.compile.data) 就是表達式經過 this.compile.data 計算后我們所需要的值。

compile text node

我們前面只講了如何編譯 node.nodeType === 1 的元素節點,那么文字節點如何編譯呢,其實理解了前面所講的內容話,文字節點的編譯就簡單得不能再簡單了:

  1. /** 
  2.  * compile text node 
  3.  * 
  4.  * @param {Node} node 
  5.  */ 
  6. Compile.compile.textNodes = function (node) { 
  7.     if (node.textContent.trim() === ''return false
  8.  
  9.     this.bindDirective({ 
  10.         node, 
  11.         name'text'
  12.         expression: parse.text(node.textContent), 
  13.     }); 
  14. };  

通過綁定 text 指令,并傳入解析后的 JavaScript 表達式,在 Directive 內部就會計算出表達式實際的值并調用 text 的 update 函數更新視圖完成渲染。

:each 指令

到目前為止,該模板引擎只實現了比較基本的功能,而最常見且重要的列表渲染功能還沒有實現,所以我們現在要實現一個 :each 指令來渲染一個列表,這里可能要注意一下,不能按照前面兩個指令的思路來實現,應該換一個角度來思考,列表渲染其實相當于一個「子模板」,里面的變量存在于 :each 指令所接收的 data 這個「局部作用域」中,這么說可能抽象,直接上代碼:

  1. // :each updater 
  2. import Compile from 'path/to/compile.js'
  3. export default { 
  4.     beforeUpdate() { 
  5.         this.placeholder = document.createComment(`:each`); 
  6.         this.node.parentNode.replaceChild(this.placeholder, this.node); 
  7.     }, 
  8.     update() { 
  9.         if (data && !Array.isArray(data)) return
  10.  
  11.         const fragment = document.createDocumentFragment(); 
  12.  
  13.         data.map((item, index) => { 
  14.             const compiled = Compile(this.node.cloneNode(true), { item, index, }); 
  15.             fragment.appendChild(compiled.view); 
  16.         }); 
  17.  
  18.         this.placeholder.parentNode.replaceChild(fragment, this.placeholder); 
  19.     }, 
  20. };  

在 update 之前,我們先把 :each 所在節點從 DOM 結構中去掉,但是要注意的是并不能直接去掉,而是要在去掉的位置插入一個 comment 類型的節點作為占位符,目的是為了在我們把列表數據渲染出來后,能找回原來的位置并把它插入到 DOM 中。

那具體如何編譯這個所謂的「子模板」呢,首先,我們需要遍歷 :each 指令所接收的 Array 類型的數據(目前只支持該類型,當然你也可以增加對 Object 類型的支持,原理是一樣的);其次,我們針對該列表的每一項數據進行一次模板的編譯并把渲染后的模板插入到創建的 document fragment 中,當所有整個列表編譯完后再把剛剛創建的 comment 類型的占位符替換為 document fragment 以完成列表的渲染。

此時,我們可以這么使用 :each 指令:

  1. Compile(`<li :each="comments" data-index="{{ index }}">{{ item.content }}</li>`, { 
  2.     comments: [{ 
  3.         content: `Hello World.`, 
  4.     }, { 
  5.         content: `Just Awesome.`, 
  6.     }, { 
  7.         content: `WOW, Just WOW!`, 
  8.     }], 
  9. });  

會渲染成:

  1. <li data-index="0">Hello World.</li> 
  2.  
  3. <li data-index="1">Just Awesome.</li> 
  4.  
  5. <li data-index="2">WOW, Just WOW!</li>  

其實細心的話你會發現,模板中使用的 item 和 index 變量其實就是 :each 更新函數中 Compile(template, data) 編譯器里的 data 值的兩個 key 值。所以要自定義這兩個變量也是非常簡單的:

  1. // :each updater 
  2. import Compile from 'path/to/compile.js'
  3. export default { 
  4.     beforeUpdate() { 
  5.         this.placeholder = document.createComment(`:each`); 
  6.         this.node.parentNode.replaceChild(this.placeholder, this.node); 
  7.  
  8.         // parse alias 
  9.         this.itemName = `item`; 
  10.         this.indexName = `index`; 
  11.         this.dataName = this.expression; 
  12.  
  13.         if (this.expression.indexOf(' in ') != -1) { 
  14.             const bracketRE = /\(((?:.|\n)+?)\)/g; 
  15.             const [item, data] = this.expression.split(' in '); 
  16.             let matched = null
  17.  
  18.             if (matched = bracketRE.exec(item)) { 
  19.                 const [item, index] = matched[1].split(','); 
  20.                 index ? this.indexName = index.trim() : ''
  21.                 this.itemName = item.trim(); 
  22.             } else { 
  23.                 this.itemName = item.trim(); 
  24.             } 
  25.  
  26.             this.dataName = data.trim(); 
  27.         } 
  28.  
  29.         this.expression = this.dataName; 
  30.     }, 
  31.     update() { 
  32.         if (data && !Array.isArray(data)) return
  33.  
  34.         const fragment = document.createDocumentFragment(); 
  35.  
  36.         data.map((item, index) => { 
  37.             const compiled = Compile(this.node.cloneNode(true), { 
  38.                 [this.itemName]: item, 
  39.                 [this.indexName]: index
  40.             }); 
  41.             fragment.appendChild(compiled.view); 
  42.         }); 
  43.  
  44.         this.placeholder.parentNode.replaceChild(fragment, this.placeholder); 
  45.     }, 
  46. };  

這樣一來我們就可以通過 (aliasItem, aliasIndex) in items 來自定義 :each 指令的 item 和 index 變量了,原理就是在 beforeUpdate 的時候去解析 :each 指令的表達式,提取相關的變量名,然后上面的例子就可以寫成這樣了:

  1. Compile(`<li :each="(comment, index) in comments" data-index="{{ index }}">{{ comment.content }}</li>`, { 
  2.     comments: [{ 
  3.         content: `Hello World.`, 
  4.     }, { 
  5.         content: `Just Awesome.`, 
  6.     }, { 
  7.         content: `WOW, Just WOW!`, 
  8.     }], 
  9. });  

Conclusion

到這里,其實一個比較簡單的模板引擎算是實現了,當然還有很多地方可以完善的,比如可以增加 :class, :style, :if 或 :src 等等你可以想到的指令功能,添加這些功能都是非常的簡單的。

全篇介紹下來,整個核心無非就是遍歷整個模板的節點樹,其次針對每一個節點的字符串值來解析成對應的表達式,然后通過 new Function() 這個構造函數來計算成實際的值,最終通過指令的 update 函數來更新到視圖上。

如果還是不清楚這些指令如何編寫的話,可以參考我這個項目 colon 的相關源碼(部分代碼可能會有不影響理解的細微差別,可忽略),有任何問題都可以在 issue 上提。

目前有一個局限就是 DOM-based 的模板引擎只適用于瀏覽器端,目前筆者也正在實現兼容 Node 端的版本,思路是把字符串模板解析成 AST,然后把更新數據到 AST 上,***再把 AST 轉成字符串模板,實現出來后有空的話再來介紹一下 Node 端的實現。

***,如果上面有說得不對或者有更好的實現方式的話,歡迎指出討論。

責任編輯:龐桂玉 來源: segmentfault
相關推薦

2017-03-20 17:59:19

JavaScript模板引擎

2017-03-15 08:43:29

JavaScript模板引擎

2021-01-28 07:21:13

算法虛擬DOM前端

2024-05-28 10:14:31

JavaScrip模板引擎

2021-09-13 06:03:42

CSS 技巧搜索引擎

2017-07-07 15:54:26

Linux監控場景

2014-02-14 09:37:01

JavascriptDOM

2021-11-01 12:25:56

Redis分布式

2023-04-08 10:04:45

2011-10-25 09:28:30

Node.js

2021-02-04 10:22:32

前端開發技術

2023-02-13 14:47:32

人工智能機器學習ChatGPT

2017-12-12 15:24:32

Web Server單線程實現

2021-06-30 07:19:36

網絡安全

2022-03-14 10:02:03

散列表鏈表哈希表

2016-09-28 17:34:27

JavaScriptvueWeb

2022-03-24 14:58:02

Java散列表編程語言

2022-03-21 08:49:01

存儲引擎LotusDB

2020-07-28 16:50:18

Javascriptkute.js前端

2023-02-26 01:37:57

goORM代碼
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 综合国产 | 成年人免费网站 | 一区欧美| 国产精品视频中文字幕 | 一级毛片在线视频 | 日日夜夜精品视频 | 亚洲三级在线观看 | 久久久久国产一区二区 | 欧美一区二区三区在线观看 | 亚洲成av人片在线观看 | 久久国产精品一区 | 欧美性一区二区三区 | 日本不卡一区二区三区 | 懂色一区二区三区免费观看 | 国产精品一区免费 | 国产乡下妇女做爰 | 中文字幕在线观看av | 国产精品不卡一区 | 亚洲一一在线 | 亚洲成在线观看 | 久久亚洲综合 | 免费h在线 | 久国久产久精永久网页 | 欧美 日韩 国产 成人 在线 91 | h片在线观看网站 | 色婷婷一区二区三区四区 | 在线啊v | 午夜99| 日韩在线视频一区二区三区 | 国产一级一级毛片 | 久久91| 国产日本精品视频 | 亚洲a视频 | 欧美一二三 | 欧美一区二区三区在线 | 欧美精品乱码久久久久久按摩 | 99精品国产一区二区三区 | 久久久综合久久 | 视频在线h | 欧美日韩在线精品 | 精品久久久久久久久久 |