js实现模板
模板引擎的实现
在JavaScript中实现模板引擎通常涉及字符串解析和变量替换。以下是几种常见的实现方式:
字符串替换法
最简单的模板引擎可以通过字符串替换实现:
function render(template, data) {
return template.replace(/\$\{(\w+)\}/g, (match, key) => data[key] || '');
}
const template = 'Hello, ${name}!';
const data = { name: 'World' };
console.log(render(template, data)); // 输出: Hello, World!
带逻辑的模板引擎
更复杂的模板引擎支持条件判断和循环:
function render(template, data) {
const evalExpr = (expr, data) => {
try {
return new Function('data', `with(data){return ${expr}}`)(data);
} catch (e) {
return '';
}
};
return template.replace(/<%=(.+?)%>/g, (_, expr) => evalExpr(expr, data))
.replace(/<%(.+?)%>/g, (_, expr) => {
new Function('data', `with(data){${expr}}`)(data);
return '';
});
}
const template = `
<% if (show) { %>
<h1><%= title %></h1>
<% } %>
`;
const data = { show: true, title: 'Welcome' };
console.log(render(template, data));
使用Function构造函数
利用JavaScript的Function构造函数可以创建更强大的模板引擎:
function compile(template) {
const evalExpr = /<%=(.+?)%>/g;
const expr = /<%([\s\S]+?)%>/g;
template = template
.replace(evalExpr, '`); \n echo( $1 ); \n echo(`')
.replace(expr, '`); \n $1 \n echo(`');
template = 'echo(`' + template + '`);';
const script =
`(function parse(data) {
const output = [];
function echo(html) {
output.push(html);
}
${template}
return output.join('');
})`;
return new Function('return ' + script)();
}
const template = `
<ul>
<% for(let i=0; i<data.length; i++) { %>
<li><%= data[i] %></li>
<% } %>
</ul>
`;
const parse = compile(template);
console.log(parse(['apple', 'orange', 'banana']));
使用ES6模板字符串
现代JavaScript可以直接使用模板字符串:
function render(template, data) {
return new Function('data', `return \`${template}\`;`)(data);
}
const template = `
${data.items.map(item => `
<div class="item">
<h2>${item.title}</h2>
<p>${item.content}</p>
</div>
`).join('')}
`;
const data = {
items: [
{ title: 'Item 1', content: 'Content 1' },
{ title: 'Item 2', content: 'Content 2' }
]
};
console.log(render(template, data));
安全考虑
实现模板引擎时需要注意XSS防护:

function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function safeRender(template, data) {
return template.replace(/\$\{(\w+)\}/g, (match, key) =>
escapeHtml(data[key] || '')
);
}
这些方法展示了从简单到复杂的JavaScript模板引擎实现方式,可以根据项目需求选择适合的方案。






