前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >【Javascript】用 js 写一个模板引擎

【Javascript】用 js 写一个模板引擎

作者头像
前端修罗场
发布2023-10-07 16:48:29
发布2023-10-07 16:48:29
20400
代码可运行
举报
文章被收录于专栏:Web 技术Web 技术
运行总次数:0
代码可运行

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

先上代码:

代码语言:javascript
代码运行次数:0
复制
<!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, \'&amp;\').replace(/"/g, \'&quot;\').replace(/\'/g, \'&#39;\').replace(/</g, \'&lt;\').replace(/>/g, \'&gt;\'); };'],
		        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)) {
		        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正则表达式熟练应用。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档