I've had a little utility that I've been kicking around for some time now that I've found to be quite useful in my JavaScript application-building endeavors. It's a super-simple templating function that is fast, caches quickly, and is easy to use. I have a couple tricks that I use to make it real fun to mess with.

Here's the source code to the templating function (a more-refined version of this code will be in my upcoming book Secrets of the JavaScript Ninja):

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
var cache = {}; this.tmpl = function tmpl(str, data){
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
var fn = !/\W/.test(str) ?
cache[str] = cache[str] ||
tmpl(document.getElementById(str).innerHTML) : // Generate a reusable function that will serve as a template
// generator (and which will be cached).
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" + // Introduce the data as local variables using with(){}
"with(obj){p.push('" + // Convert the template into pure JavaScript
str
.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'")
+ "');}return p.join('');"); // Provide some basic currying to the user
return data ? fn( data ) : fn;
};
})();
 

You would use it against templates written like this (it doesn't have to be in this particular manner - but it's a style that I enjoy):

<script type="text/html" id="item_tmpl">
<div id="<%=id%>" class="<%=(i % 2 == 1 ? " even" : "")%>">
<div class="grid_1 alpha right">
<img class="righted" src="<%=profile_image_url%>"/>
</div>
<div class="grid_6 omega contents">
<p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p>
</div>
</div>
</script>

You can also inline script:

<script type="text/html" id="user_tmpl">
<% for ( var i = 0; i < users.length; i++ ) { %>
<li><a href="<%=users[i].url%>"><%=users[i].name%></a></li>
<% } %>
</script>

Quick tip: Embedding scripts in your page that have a unknown content-type (such is the case here - the browser doesn't know how to execute a text/html script) are simply ignored by the browser - and by search engines and screenreaders. It's a perfect cloaking device for sneaking templates into your page. I like to use this technique for quick-and-dirty cases where I just need a little template or two on the page and want something light and fast.

and you would use it from script like so:

var results = document.getElementById("results");
results.innerHTML = tmpl("item_tmpl", dataObject);

You could pre-compile the results for later use. If you call the templating function with only an ID (or a template code) then it'll return a pre-compiled function that you can execute later:

var show_user = tmpl("item_tmpl"), html = "";
for ( var i = 0; i < users.length; i++ ) {
html += show_user( users[i] );
}

The biggest falling-down of the method, at this point, is the parsing/conversion code - it could probably use a little love. It does use one technique that I enjoy, though: If you're searching and replacing through a string with a static search and a static replace it's faster to perform the action with .split("match").join("replace") - which seems counter-intuitive but it manages to work that way in most modern browsers. (There are changes going in place to grossly improve the performance of .replace(/match/g, "replace") in the next version of Firefox - so the previous statement won't be the case for long.)

Feel free to have fun with it - I'd be very curious to see what mutations occur with the script. Since it's so simple it seems like there's a lot that can still be done with it.

原文地址:http://ejohn.org/blog/javascript-micro-templating/

[转] jquery作者John Resig编写的微模板引擎:JavaScript Micro-Templating的更多相关文章

  1. Handlebars的基本用法 Handlebars.js使用介绍 http://handlebarsjs.com/ Handlebars.js 模板引擎 javascript/jquery模板引擎——Handlebars初体验 handlebars.js 入门(1) 作为一名前端的你,必须掌握的模板引擎:Handlebars 前端数据模板handlebars与jquery整

    Handlebars的基本用法 使用Handlebars,你可以轻松创建语义化模板,Mustache模板和Handlebars是兼容的,所以你可以将Mustache导入Handlebars以使用 Ha ...

  2. 10 个强大的JavaScript / jQuery 模板引擎推荐

    模板引擎是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档.由于在开发过程中,网站或应用程序的界面与数据实现分离,大大提升了开发效率,良好的设计也使得代码重用变得更加容易. 本文 ...

  3. 使用 jQuery UI Widget Factory 编写有状态的插件(Stateful Plugins)

    使用 jQuery UI Widget Factory 编写有状态的插件(Stateful Plugins) Note 这一章节的内容是基于 Scott Gonzalez 一篇博客 Building ...

  4. jquery插件分类与编写详细讲解

    jquery插件分类与编写详细讲解 1. 插件种类 插件其实就是对现有的方法(或者叫函数)做一个封装,方便重用提高开发效率.   jQeury主要有2种类型   1)实例对象方法插件 开发能让所有的j ...

  5. Simple JavaScript Inheritance(John Resig)

    I’ve been doing a lot of work, lately, with JavaScript inheritance – namely for my work-in-progress ...

  6. knockoutJS学习笔记01:从拼接字符串到编写模板引擎

    开篇 关于knockout的文章,园里已经有很多大神写过了,而且都写得很好.其实knockout学习起来还是很容易的,看看官网的demo和园里的文章,练习练习就可以上手了(仅限使用,不包含研究源码). ...

  7. 如何编写可维护的面向对象JavaScript代码

    能够写出可维护的面向对象JavaScript代 码不仅可以节约金钱,还能让你很受欢迎.不信?有可能你自己或者其他什么人有一天会回来重用你的代码.如果能尽量让这个经历不那么痛苦,就可以节省不少时 间.地 ...

  8. surging 微服务引擎 2.0 会有多少惊喜?

    surging 微服务引擎从2017年6月至今已经有两年的时间,这两年时间有多家公司使用surging 服务引擎,并且有公司搭建了CI/CD,并且使用了k8s 集群,这里我可以说下几家公司的服务搭建情 ...

  9. Workflow-产品:泛微工作流引擎

    ylbtech-Workflow-产品:泛微工作流引擎 1.返回顶部 1. 工作流引擎平台技术架构 TECHNOLOGY FRAMEWORK 高度协同系统各应用模块 泛微工作流引擎平台是整个协同办公平 ...

随机推荐

  1. 三月pat(转)

    转自https://blog.csdn.net/weixin_40688413/article/details/88082779 担心别人删除了就找不到了.因为九月要考. 7-1 Sexy Prime ...

  2. h5页面在ios机上禁止长按复制

    (注意,增加之后需要对input的另外设置,不然输入框无法输入)场景:H5出现一个按钮需要长按几秒展示动画的,如:skcs.net-tactic.com/wap/peace/index,这时就需要用到 ...

  3. 《Whitelabel Error Page 404》 对于Springboot初学者可能出现问题的原因

    whitelabel error page异常一定是有原因的,比如,访问路径不对,解析不对,注解忘记引入等.对于初学者,一定要注意一点,程序只加载Application.java所在包及其子包下的内容 ...

  4. Ping 命令实战小结--TCP/IP协议学习

    2011-12-22 22:38:49 图1 图2 一,环境说明 硬件连线.PC与2440开发板直接用网线连接. PC的ip地址:192.168.0.107.2440开发板的ip地址:192.168. ...

  5. IPv4的编址方法

    重难点: 1.IP地址有3位标识符,由ICANN进行分配. 2.两级的IP地址分为 ::={<网络号>,<主机号>}. 3.在同一个局域网上的主机或路由器的IP地址中的网络号必 ...

  6. redis缓存数据库

    redis 介绍 redis是业界主流的key-value nosql 数据库之一.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set( ...

  7. 0x14哈希之兔子兔子

    参考链接:https://www.cnblogs.com/wyboooo/p/9813428.html 题目链接:https://www.acwing.com/problem/content/140/ ...

  8. NPOI 的使用姿势

    NPOI 正确的使用姿势 主要是需要注意公式和日期类型的单元格的读取. /// <summary> /// 打开指定 Excel 文件 /// </summary> /// & ...

  9. 深度学习网络中numpy多维数组的说明

    目前在计算机视觉中应用的数组维度最多有四维,可以表示为 (Batch_size, Row, Column, Channel) 以下将要从二维数组到四维数组进行代码的简单说明: Tips: 1) 在nu ...

  10. TCP 传输控制协议

    开头先说几个协议: IP:网际协议 TCP:传输控制协议 Http:超文本传输协议 AMQP:高级消息队列协议 一:TCP是什么? TCP(Transmission Control Protocol ...