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. Maven不能下载SNAPSHOT包但是能下载RELEASE包的解决办法

    在使用过程中,Maven默认配置是不能下载SNAPSHOT包的,这是基于一种代码稳定性进行考量得出的结论.引入SNAPSHOT包最大的问题就是,由于SNAPSHOT允许重复上传,所以引用一个这样的包开 ...

  2. Mac 下 实现终端跳转 服务器 不用输入密码

    首先需要安装 expect 安装 expect  需要 tcl 依赖 第一步 下载tcl http://www.tcl.tk/software/tcltk/downloadnow84.tml 将下载好 ...

  3. C博客第02次作业---循环结构

    1.本章学习总结 1.1 思维导图 1.2 本章学习体会及代码量 1.2 本章学习体会及代码量 1.2.1 学习体会 1.这两周的学习懂得了循环结构的使用方法,懂得了在什么时候应该使用循环结构来处理问 ...

  4. IP通信基础的第一个星期

    IP通信基础不仅是很多专业课程的基础,同时学好它,在以后很多工作上都可以运用到,有网络工程师.通信工程师等等,当然,有些证书也会涉及到IP通信基础,有网络中级高级 CCNA等等. 那么,学好IP通信基 ...

  5. es7,es8

    ES7新特性 ES7在ES6的基础上添加了三项内容:求幂运算符(**).Array.prototype.includes()方法.函数作用域中严格模式的变更. Array.prototype.incl ...

  6. javascript声明变量

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  7. Character

    Character a = new Character(); Character.isUpperCase(a) 判断给点的字符是否是大写字符 Character.isLowerCase(a) 判断给定 ...

  8. JAVA获取计算机IP地址

    import java.net.InetAddress;import java.net.UnknownHostException;public class HuoQu {    public stat ...

  9. Developing Vert.x Modules using the Standard Project

    The module The tests Unit tests Integration tests Java integration tests JavaScript integration test ...

  10. mysqli_query($conn, $sql)的返回值类型

    SQL语句的分类: DDL: Data Define Language,数据定义语言——定义列 CREATE / DROP / ALTER / TRUNCATE DML: Data Manipulat ...