题图:Vincent Guth
注:本文所有代码均可在本人的小我项目colon中找到,本文也同步到了知乎专栏
可能你已经领会到了 Vue 所带来的便捷了,信赖有一部分原因也是因为其基于 DOM 的语法简洁的模板衬着引擎。这篇文┞仿将会介绍若何实现一个基于 DOM 的模板引擎(就像 Vue 的模板引擎一样)。
Preface
开端之前,我们先来看一下最终的效不雅:
- const compiled = Compile(`<h1>Hey 🌰, {{ greeting }}</h1>`, {
- greeting: `Hello World`,
- });
- compiled.view // => `<h1>Hey 🌰, Hello World</h1>`
Compile
实现一个模板引擎实际上就是实现一个编译器,就像如许:
- const compiled = Compile(template: String|Node, data: Object);
- compiled.view // => compiled template
起首,让我们来看下 Compile 内部是若何实现的:
- // compile.js
- /**
- * template compiler
- *
- * @param {String|Node} template
- * @param {Object} data
- */
- function Compile(template, data) {
- if (!(this instanceof Compile)) return new Compile(template, data);
- this.options = {};
- this.data = data;
- if (template instanceof Node) {
- this.options.template = template;
- } else if (typeof template === 'string') {
- this.options.template = domify(template);
- } else {
- console.error(`"template" only accept DOM node or string template`);
- }
- template = this.options.template;
- walk(template, (node, next) => {
- if (node.nodeType === 1) {
- // compile element node
- this.compile.elementNodes.call(this, node);
- return next();
- } else if (node.nodeType === 3) {
- // compile text node
推荐阅读
曾经和格力电器董事长董明珠有10亿赌约的小米,要做空调了? 8月10日,小米智能硬件生态链企业智米科技宣布了一款售价4399元的全直流变频空调,但品牌不是“小米&rdqu>>>详细阅读
本文标题:如何实现一个基于DOM的模板引擎
地址:http://www.17bianji.com/lsqh/36664.html
1/2 1