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

题图:Vincent Guth

坚守“ 做人真诚 · 做事靠谱 · 口碑至上 · 高效敬业 ”的价值观,专业网站建设服务10余年为成都地磅秤小微创业公司专业提供企业网站制作营销网站建设商城网站建设手机网站建设小程序网站建设网站改版,从内容策划、视觉设计、底层架构、网页布局、功能开发迭代于一体的高端网站建设服务。

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

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

Preface

开始之前,我们先来看一下最终的效果:

 
 
 
  1. const compiled = Compile(`

    Hey , {{ greeting }}

    `, {
  2.     greeting: `Hello World`,
  3. });
  4. compiled.view // => `

    Hey , Hello World

Compile

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

 
 
 
  1. const compiled = Compile(template: String|Node, data: Object);
  2. 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.     this.options = {};
  11.     this.data = data;
  12.     if (template instanceof Node) {
  13.         this.options.template = template;
  14.     } else if (typeof template === 'string') {
  15.         this.options.template = domify(template);
  16.     } else {
  17.         console.error(`"template" only accept DOM node or string template`);
  18.     }
  19.     template = this.options.template;
  20.     walk(template, (node, next) => {
  21.         if (node.nodeType === 1) {
  22.             // compile element node
  23.             this.compile.elementNodes.call(this, node);
  24.             return next();
  25.         } else if (node.nodeType === 3) {
  26.             // compile text node
  27.             this.compile.textNodes.call(this, node);
  28.         }
  29.         next();
  30.     });
  31.     this.view = template;
  32.     template = null;
  33. }
  34. 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.     attributes.map(attribute => {
  13.         attrName = attribute.name;
  14.         attrValue = attribute.value.trim();
  15.         if (attrName.indexOf(bindSymbol) === 0 && attrValue !== '') {
  16.             directiveName = attrName.slice(bindSymbol.length);
  17.             this.bindDirective({
  18.                 node,
  19.                 expression: attrValue,
  20.                 name: directiveName,
  21.             });
  22.             node.removeAttribute(attrName);
  23.         } else {
  24.             this.bindAttribute(node, attribute);
  25.         }
  26.     });
  27. }; 

噢忘记说了,这里我参考了 Vue 的指令语法,就是在带有冒号 : 的属性名中(当然这里也可以是任何其他你所喜欢的符号),可以直接写 JavaScript 的表达式,然后也会提供几个特殊的指令,例如 :text, :show 等等来对元素做一些不同的操作。

其实该函数只做了两件事:

  • 遍历该节点的所有属性,通过判断属性类型的不同来做不同的操作,判断的标准就是属性名是否是冒号 : 开头并且属性的值不为空;
  • 绑定相应的指令去更新属性。

Directive

其次,再看一下 Directive 内部是如何实现的:

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

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. Compile.prototype.bindAttribute = function (node, attribute) {
  8.     if (!hasInterpolation(attribute.value) || attribute.value.trim() == '') return false;
  9.     this.bindDirective({
  10.         node,
  11.         name: 'attribute',
  12.         expression: parse.text(attribute.value),
  13.         attrName: attribute.name,
  14.     });
  15. }; 

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(``, {
  2.     greeting: `Hello World`,
  3. });
  4. compiled.view // => `

    Hey , Hello World

    `

generate

讲到这里,其实还有一个非常重要的点没有提到,就是我们如何把 data 真实数据渲染到模板中,比如

Hey , {{ greeting }}

如何渲染成

Hey , Hello World

,通过下面三个步骤即可计算出表达式的真实数据:

  • Hey , {{ greeting }}

    解析成 '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.     const tokens = [];
  6.     let lastIndex = tagRE.lastIndex = 0;
  7.     let index, matched;
  8.     while (matched = tagRE.exec(text)) {
  9.         index = matched.index;
  10.         if (index > lastIndex) {
  11.             tokens.push(JSON.stringify(text.slice(lastIndex, index)));
  12.         }
  13.         tokens.push(matched[1].trim());
  14.         lastIndex = index + matched[0].length;
  15.     }
  16.     if (lastIndex < text.length) tokens.push(JSON.stringify(text.slice(lastIndex)));
  17.     return tokens.join('+');

该函数我是直接参考 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. function extractDependencies(expression) {
  8.     const dependencies = [];
  9.     expression.replace(dependencyRE, (match, dependency) => {
  10.         if (
  11.             dependency !== undefined &&
  12.             dependencies.indexOf(dependency) === -1 &&
  13.             globals.indexOf(dependency) === -1
  14.         ) {
  15.             dependencies.push(dependency);
  16.         }
  17.     });
  18.     return dependencies;

通过正则表达式 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.     dependencies.map(dependency => dependenciesCode += `var ${dependency} = this.get("${dependency}"); `);
  5.     return new Function(`data`, `${dependenciesCode}return ${expression};`);

我们提取变量的目的就是为了在 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. // will generated:
  8. function anonymous(data) {
  9.     var name = data["name"];
  10.     var world = data["world"];
  11.     var hello = data["hello"];
  12.     return typeof String(name) === 'string'  && 'Hello ' + world + '! ' + hello.split('').join('') + '.';

这样的话,只需要在调用这个匿名函数的时候传入对应的 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.     }

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.     this.bindDirective({
  9.         node,
  10.         name: 'text',
  11.         expression: parse.text(node.textContent),
  12.     });
  13. }; 

通过绑定 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.         const fragment = document.createDocumentFragment();
  11.         data.map((item, index) => {
  12.             const compiled = Compile(this.node.cloneNode(true), { item, index, });
  13.             fragment.appendChild(compiled.view);
  14.         });
  15.         this.placeholder.parentNode.replaceChild(fragment, this.placeholder);
  16.     },
  17. }; 

在 update 之前,我们先把 :each 所在节点从 DOM 结构中去掉,但是要注意的是并不能直接去掉,而是要在去掉的位置插入一个 comment 类型的节点作为占位符,目的是为了在我们把列表数据渲染出来后,能找回原来的位置并把它插入到 DOM 中。

那具体如何编译这个所谓的「子模板」呢,首先,我们需要遍历 :each 指令所接收的 Array 类型的数据(目前只支持该类型,当然你也可以增加对 Object 类型的支持,原理是一样的);其次,我们针对该列表的每一项数据进行一次模板的编译并把渲染后的模板插入到创建的 document fragment 中,当所有整个列表编译完后再把刚刚创建的 comment 类型的占位符替换为 document fragment 以完成列表的渲染。

此时,我们可以这么使用 :each 指令:

 
 
 
  1. Compile(`{{ item.content }}
  2. `, {
  3.     comments: [{
  4.         content: `Hello World.`,
  5.     }, {
  6.         content: `Just Awesome.`,
  7.     }, {
  8.         content: `WOW, Just WOW!`,
  9.     }],
  10. }); 

会渲染成:

 
 
 
  1. Hello World.
  2. Just Awesome.
  3. WOW, Just WOW!
  4.  

其实细心的话你会发现,模板中使用的 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.         // parse alias
  8.         this.itemName = `item`;
  9.         this.indexName = `index`;
  10.         this.dataName = this.expression;
  11.         if (this.expression.indexOf(' in ') != -1) {
  12.             const bracketRE = /\(((?:.|\n)+?)\)/g;
  13.             const [item, data] = this.expression.split(' in ');
  14.             let matched = null;
  15.             if (matched = bracketRE.exec(item)) {
  16.                 const [item, index] = matched[1].split(',');
  17.                 index ? this.indexName = index.trim() : '';
  18.                 this.itemName = item.trim();
  19.             } else {
  20.                 this.itemName = item.trim();
  21.             }
  22.             this.dataName = data.trim();
  23.         }
  24.         this.expression = this.dataName;
  25.     },
  26.     update() {
  27.         if (data && !Array.isArray(data)) return;
  28.         const fragment = document.createDocumentFragment();
  29.         data.map((item, index) => {
  30.             const compiled = Compile(this.node.cloneNode(true), {
  31.                 [this.itemName]: item,
  32.                 [this.indexName]: index,
  33.             });
  34.             fragment.appendChild(compiled.view);
  35.         });
  36.         this.placeholder.parentNode.replaceChild(fragment, this.placeholder);
  37.     },
  38. }; 

这样一来我们就可以通过 (aliasItem, aliasIndex) in items 来自定义 :each 指令的 item 和 index 变量了,原理就是在 beforeUpdate 的时候去解析 :each 指令的表达式,提取相关的变量名,然后上面的例子就可以写成这样了:

 
 
 
  1. Compile(`{{ comment.content }}
  2. `, {
  3.     comments: [{
  4.         content: `Hello World.`,
  5.     }, {
  6.         content: `Just Awesome.`,
  7.     }, {
  8.         content: `WOW, Just WOW!`,
  9.     }],
  10. }); 

Conclusion

到这里,其实一个比较简单的模板引擎算是实现了,当然还有很多地方可以完善的,比如可以增加 :class, :style, :if 或 :src 等等你可以想到的指令功能,添加这些功能都是非常的简单的。

全篇介绍下来,整个核心无非就是遍历整个模板的节点树,其次针对每一个节点的字符串值来解析成对应的表达式,然后通过 new Function() 这个构造函数来计算成实际的值,最终通过指令的 update 函数来更新到视图上。

如果还是不清楚这些指令如何编写的话,可以参考我这个项目 colon 的相关源码(部分代码可能会有不影响理解的细微差别,可忽略),有任何问题都可以在 issue 上提。

目前有一个局限就是 DOM-based 的模板引擎只适用于浏览器端,目前笔者也正在实现兼容 Node 端的版本,思路是把字符串模板解析成 AST,然后把更新数据到 AST 上,***再把 AST 转成字符串模板,实现出来后有空的话再来介绍一下 Node 端的实现。

***,如果上面有说得不对或者有更好的实现方式的话,欢迎指出讨论。

网站名称:如何实现一个基于DOM的模板引擎
URL链接:http://www.shufengxianlan.com/qtweb/news15/155765.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联