您的位置:首页 > Web前端 > JavaScript

【分享/转】用js写一个模板引擎

2016-05-06 16:58 661 查看
优质文章分享:http://lvtraveler.github.io/

模板引擎在前后端都能用到,但是通过作为前端,我们只需要一些简单的模板引擎。

先上代码:

<!DOCTYPE html>
<html>
<head>
<title>模板引擎</title>
</head>
<body>
<div id="tpl" type="text/plain">
<p>Today: { date }</p>
<a href="/{ user.id|safe }">{ user.company }</a>
</div>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
var tpl = new Template($('#tpl').html());
var date= new Date();
var model = tpl.render({
date: date,
user: {
id: '0000',
company: 'babybus'
}
});
$('#tpl').html(model);
function Template(tpl) {
var
fn,
match,
code = ['var r=[];\nvar _html = function (str) { return str.replace(/&/g, \'&\').replace(/"/g, \'"\').replace(/\'/g, \''\').replace(/</g, \'<\').replace(/>/g, \'>\'); };'],
re = /\{\s*([a-zA-Z\.\_0-9()]+)(\s*\|\s*safe)?\s*\}/m,
addLine = function (text) {
code.push('r.push(\'' + text.replace(/\'/g, '\\\'').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '\');');
};
while (match = re.exec(tpl)) {

c4de
if (match.index > 0) {
addLine(tpl.slice(0, match.index));
}
if (match[2]) {
code.push('r.push(String(this.' + match[1] + '));');
}
else {
code.push('r.push(_html(String(this.' + match[1] + ')));');
}
tpl = tpl.substring(match.index + match[0].length);
}
addLine(tpl);
code.push('return r.join(\'\');');
fn = new Function(code.join('\n'));
this.render = function (model) {
return fn.apply(model);
};
}
</script>

</body>
</html>


这个我们能用这个模板引擎创建一个我们前端需要的html片段了。

这里面我们使用正则表达式去匹配字符串中的变量,当然,你要对js正则表达式熟练应用。

原文地址:http://www.liaoxuefeng.com/article/001426512790239f83bfb47b1134b63b09a57548d06e5c5000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: