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. angular2 学习笔记 ( app initialize 初始化 )

    refer : http://stackoverflow.com/questions/39033835/angularjs2-preload-server-configuration-before-t ...

  2. restful架构风格设计准则(二)以资源为中心,一个url

    读书笔记,原文链接:http://www.cnblogs.com/loveis715/p/4669091.html,感谢作者! 1.REST是一种架构风格,其核心是面向资源,简化设计,降低开发的复杂性 ...

  3. C#程序编写规范

    代码书写规则 1.尽量使用接口,然后使用类实现接口,提高程序的灵活性. 2.一行不要超过80个字符. 3.尽量不要手工更改计算机生成的代码,若必须要改,一定要改为和计算机生成的代码风格一样. 4.关键 ...

  4. POJ- 1094 Sorting It All Out---拓扑排序是否唯一的判断

    题目链接: https://vjudge.net/problem/POJ-1094 题目大意: 该题题意明确,就是给定一组字母的大小关系判断他们是否能组成唯一的拓扑序列.是典型的拓扑排序,但输出格式上 ...

  5. NSDateFormatter常见的使用方式

    NSDateFormatter是NSFormatter的子类,是用来表示输出的时间格式. 下面贴出两个时间的例子. 例子一. - (void)dateString1 { NSDateFormatter ...

  6. 云如何让App开发更简单?

    欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 互联网"下半场",移动App开发对于质量.速度的要求更加苛刻.4月初,腾讯云正式上线移动开发平台MobileLine,借 ...

  7. getgpc($k, $t='GP'),怎么返回的是 NULL?

    <?php /** * 实用小代码 * 获得GET POST COOKIS */ $html=<<<WORD <form method="post"& ...

  8. springboot快速入门

    SpringBoot简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再 ...

  9. SQL SERVER之查询外键及索引

    --查询表或数据库中的所有外键 select A.name as 约束名, object_name(b.parent_object_id) as 外健表, c.name as 外键列, object_ ...

  10. R语言-美国枪杀案分析

    案例:该数据集的是一个关于美国2017年犯罪的一个数据集,接下来我们对该数据集进行分析 字段: #### S# :数据编号 #### Location:案件发生城市,州 #### Date:时间 ## ...