js实现 template
实现模板引擎的基本方法
在JavaScript中实现模板引擎可以通过多种方式完成,以下是一些常见的方法:
字符串替换法
使用字符串的replace方法配合正则表达式进行简单替换:
function render(template, data) {
return template.replace(/\{\{(\w+)\}\}/g, (match, key) => data[key] || '');
}
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) {
let output = "";
function echo(html) {
output += html;
}
${template}
return output;
})`;
return new Function('data', script);
}
使用ES6模板字符串
现代JavaScript可以利用模板字符串的特性实现模板渲染:
function render(template, data) {
return new Function('data', `return \`${template}\``)(data);
}
实现条件判断和循环
更高级的模板引擎需要支持逻辑控制:

function compile(template) {
const tokens = template.split(/(<%[\s\S]*?%>)/g);
let code = 'let output = "";\n';
tokens.forEach(token => {
if (token.startsWith('<%=')) {
code += `output += ${token.slice(3, -2)};\n`;
} else if (token.startsWith('<%')) {
code += `${token.slice(2, -2)}\n`;
} else {
code += `output += \`${token}\`;\n`;
}
});
code += 'return output;';
return new Function('data', code);
}
安全考虑
实现模板引擎时需要注意XSS防护:
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function safeRender(template, data) {
return render(template, {
...data,
_: escapeHtml
});
}
性能优化
对于频繁使用的模板可以预编译:
const cache = {};
function compileAndCache(template) {
if (!cache[template]) {
cache[template] = compile(template);
}
return cache[template];
}
以上方法展示了从简单到复杂的JavaScript模板引擎实现方式,可以根据具体需求选择合适的实现方案。






