JavaScript Micro-Templating

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
(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.

javascript templating的更多相关文章

  1. JavaScript资源大全中文版(Awesome最新版)

    Awesome系列的JavaScript资源整理.awesome-javascript是sorrycc发起维护的 JS 资源列表,内容包括:包管理器.加载器.测试框架.运行器.QA.MVC框架和库.模 ...

  2. 最简单的JavaScript模板引擎

    在小公司待久了感觉自己的知识面很小,最近逛博客园和一些技术网站看大家在说JavaScript模版引擎的事儿,完全没有概念,网上一搜这是08年开始流行起来的...本来以为这是很高深的知识,后来在网上看到 ...

  3. 简单JavaScript模版引擎优化

    在上篇博客最简单的JavaScript模板引擎 说了一下一个最简单的JavaScript模版引擎的原理与实现,作出了一个简陋的版本,今天优化一下,使之能够胜任日常拼接html工作,先把上次写的模版函数 ...

  4. JavaScript 模板引擎实现原理解析

    1.入门实例 首先我们来看一个简单模板: <script type="template" id="template"> <h2> < ...

  5. 【JavsScript】推荐五款流行的JavaScript模板引擎

    摘要:Javascript模板引擎作为数据与界面分离工作中最重要一环,受到开发者广泛关注.本文通过开发实例解析五款流行模板引擎:Mustache.Underscore Templates.Embedd ...

  6. Micro Templating源码分析

    关于模板,写页面的人们其实一直在用,asp.net , jsp , php, nodejs等等都有他的存在,当然那是服务端的模板. 前端模板,作为前端人员肯定是多少有接触的,Handlebars.js ...

  7. [转] jquery作者John Resig编写的微模板引擎:JavaScript Micro-Templating

    I've had a little utility that I've been kicking around for some time now that I've found to be quit ...

  8. Javascript模版引擎简介

    回顾 Micro-Templating 出自John Resig 2008年的一片文章,以及其经典实现: // Simple JavaScript Templating // John Resig - ...

  9. JavaScript模板引擎使用

    1. [代码]tmpl.js     // Simple JavaScript Templating// John Resig - http://ejohn.org/ - MIT Licensed(f ...

随机推荐

  1. restful架构风格设计准则(三)资源识别和资源设计

    读书笔记,原文链接:http://www.cnblogs.com/loveis715/p/4669091.html,感谢作者! restful风格的设计中,首先要识别系统中的资源,然后用HTTP规范表 ...

  2. SLF4J - 借助SLF4J, 统一适配所有日志实现为logback日志实现的实践

    一.屏蔽各种日志实现,去掉各种日志实现的实现依赖 二.引入slf4j和各种日志实现的适配器 1.引入slf4j 2.引入各种日志实现的适配器(适配到slf4j) 3.引入logback 引入logba ...

  3. 阿里云API网关(3)快速入门(调用 API)

    网关指南: https://help.aliyun.com/document_detail/29487.html?spm=5176.doc48835.6.550.23Oqbl 网关控制台: https ...

  4. MongoDB GridFS 存储大文件

    我们经常会遇到这样的场景:上传/下载文件. 有两种思路可以解决这个问题: (1)将文件存储在服务器的文件系统中: (2)将文件存储在数据库中. 如果我们选择(2),那么我们可以使用MongoDB Gr ...

  5. vue2路由

    我们在前面的学习过程中不管是在学习angular还是vue1,都会遇到二级路由,我们现在先来看一下vue2中的一级路由. 首先要引入的是vue2与路由文件. js代码: <script> ...

  6. SpringMVC(十):SpringMVC 处理输出模型数据之Map及Model

    Spring MVC提供了以下几种途径输出模型数据: 1)ModelAndView:处理方法返回值类型为ModelAndView时,方法体即可通过该对象添加模型数据: 2)Map及Model:处理方法 ...

  7. LabelFrame

    LabelFrame组件是Frame组件的变体. 默认情况下,LabelFrame会在其子组件的周围绘制一个边框以及一个标题. 何时使用LabelFrame组件?当你想要奖一些相关的组件分为一组的时候 ...

  8. FTP下载文件

    linux命令方式下载 step1: >>ftp ip port 根据提示输入用户名 根据提示输入用户密码 >>cd 目录(重要:一定要进入文件所在的目录) >>g ...

  9. 输出一个对象,会默认执行toString()方法

    今天在看编程思想时看到enum知识点时发现了这个小问题(可能我基础太差了) 如图 然后就一步一步的跟进源码发现了其中的奥秘,首先进入println()方法如下图 看图执行了valueOf()方法进行s ...

  10. JS继承的一些见解

    JS继承的一些见解 js在es6之前的继承是五花八门的.而且要在项目中灵活运用面向对象写法也是有点别扭,更多的时候还是觉得面向过程的写法更为简单,效率也高.久而久之对js的继承每隔一段时间就会理解出现 ...