纯JS实现一个模板引擎
我用了11行代码实现了。
// tpl.js文件
function tpljs(tplStr) {
const compile = (tplStr) => {
return tplStr.replace(/(\{%|%\})/g, (...args) => {
return args[1] === '{%' ? '`;' : 'str+=`';
}).replace(/\s*(`)\s*/g, '$1');
}
const fn = new Function('data', 'let str=""; with(data){ str+=`'+compile(tplStr)+'`; return str; }');
return function render(data) {
return fn(data);
}
}
测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>测试tpl.js</title>
</head>
<body>
<div id="app"></div>
<template id="tpl">
{% let i = 0; %}
{% for(let item of list){ %}
<div class="list-item">${i} - ${item.name}</div>
{% i++; %}
{% } %}
</template>
<!-- 引用上面的tpl.js -->
<script src="./tpl.js"></script>
<script>
const app = document.querySelector('#app');
const tpl = document.querySelector('#tpl');
const render = tpljs(tpl.innerHTML);
app.innerHTML = render({
list: [
{ name: '入门指南' },
{ name: '组件库' },
{ name: '文档' },
]
});
</script>
</body>
</html>
效果