在前后端未分家的年代,Handlebars、EJS、Jade(Pug)这类引擎是主力:模板里写好循环与条件,后端渲染时把数据注入进去输出 HTML。它们解决了字符串拼装可读性差的问题,也是后来 Vue 模板与 JSX 编译思路的源头。
今天直接写模板引擎的场合变少了,但理解编译原理很有价值:Vue 的模板会被编译成渲染函数,JSX 也会经过 Babel 转成 createElement 调用,本质上都是把模板描述翻译成可执行的渲染指令。会读编译产物,调试与性能优化时就能看得更深。
// 极简模板引擎:占位符替换 + 循环展开(手写理解原理) function compile(tpl, data) { var out = tpl.replace(/\{\{(\w+)\}\}/g, function (_, key) { return data[key] !== undefined ? data[key] : ''; }); // 支持 {{#each list}}...{{/each}} out = out.replace(/\{\{#each (\w+)\}\}([\s\S]*?)\{\{\/each\}\}/g, function (_, key, body) { return (data[key] || []).map(function (item) { return compile(body, item); }).join(''); }); return out; } var html = compile( '<ul>{{#each items}}<li>{{name}}:{{price}} 元</li>{{/each}}</ul>', { items: [{ name: '苹果', price: 6 }, { name: '香蕉', price: 4 }] } ); console.log(html); // <ul><li>苹果:6 元</li><li>香蕉:4 元</li></ul>