0
点赞
收藏
分享

微信扫一扫

再也没有比这更快的JS模板引擎:TiniestTpl-v1.js

开篇

无聊之闲,又翻到这个JS模板引擎,然后又重写了一下,比上一次又提升了15-20%的性能。测试的时候,由于 baiduTemplate 和 jqueryTmpl模板引擎太慢,多次导致浏览器崩溃,因此在1000次编译和10000000次的渲染中没有加载这两个模板引擎。

测试截图

再也没有比这更快的JS模板引擎:TiniestTpl-v1.js_数据

再也没有比这更快的JS模板引擎:TiniestTpl-v1.js_模板引擎_02


使用方法

返回渲染函数:tiniestTpl(html)

var html = "..." , data = {...};
var render = tiniestTpl(html); //编译
var result = render(data); //重复渲染使用

返回渲染好的模板内容:tiniestTpl(html, data)

var html = "..." , data = {...};
var result = tiniestTplv1(html, data); //编译和渲染,并返回处理后的html


模板语法

类型

语法

说明

String

<!--% ..... %-->

包含判断、循环等逻辑语法块

String

<!--%=data["name"]-->

输出变量


简单的例子

<div id="tiniestTpl">
<ul>
使用原生 javascript 语法编写模板, 变量 data 为模板传入的数据
<!--% for (var val, i = 0, l = data.list.length; i < l; i ++) { %-->
<li>用户: <!--%=val.user%--> / 网站:<!--%=val.site%--></li>
<!--% } %-->
</ul>
</div>

<div id="output"></div>
var data = {
list: [
{
'user': 'stanley5050',
'site': 'https://blog.51cto.com/12641643'
}
]
};

// 示例一:
var fn = tiniestTpl(document.getElementId('tiniestTpl').innerHtml);
document.getElementId('output').innerHtml = fn(data);

// 示例二:
document.getElementId('output').innerHtml = tiniestTpl(document.getElementId('tiniestTpl').innerHtml, data);

源代码

var tiniestTplv10 = {
'tplCache': {}
};

function tiniestTplv1(html, data, fstr = '') {
if (typeof html != 'string' || !html) return '';
if (typeof tiniestTplv10.tplCache[html] == 'function') {
return data ? tiniestTplv10.tplCache[html](data) : tiniestTplv10.tplCache[html];
}

let tmp = html.replace(/[\r\n\t]/g, "").split(/<!--%/g);
let pos = 0;
tmp.forEach(segment => {
if (segment.length < 1) return;
pos = segment.indexOf('%-->');
if (segment[0] == '=') {
fstr += "__str+=" + segment.substring(1, pos) + ";__str+='" + segment.substring(pos + 4) + "';";
} else {
fstr += segment.substring(0, pos) + "__str+='" + segment.substring(pos + 4) + "';";
}
});

fstr = "func=function(data){let __str='';" + fstr + "return __str;};";
tiniestTplv10.tplCache[html] = eval(fstr);
return data ? tiniestTplv10.tplCache[html](data) : tiniestTplv10.tplCache[html];
}

下载

一年后的今天,我仍然没有找到可以上传附件的功能。

举报

相关推荐

0 条评论