javascript templating
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的更多相关文章
- JavaScript资源大全中文版(Awesome最新版)
Awesome系列的JavaScript资源整理.awesome-javascript是sorrycc发起维护的 JS 资源列表,内容包括:包管理器.加载器.测试框架.运行器.QA.MVC框架和库.模 ...
- 最简单的JavaScript模板引擎
在小公司待久了感觉自己的知识面很小,最近逛博客园和一些技术网站看大家在说JavaScript模版引擎的事儿,完全没有概念,网上一搜这是08年开始流行起来的...本来以为这是很高深的知识,后来在网上看到 ...
- 简单JavaScript模版引擎优化
在上篇博客最简单的JavaScript模板引擎 说了一下一个最简单的JavaScript模版引擎的原理与实现,作出了一个简陋的版本,今天优化一下,使之能够胜任日常拼接html工作,先把上次写的模版函数 ...
- JavaScript 模板引擎实现原理解析
1.入门实例 首先我们来看一个简单模板: <script type="template" id="template"> <h2> < ...
- 【JavsScript】推荐五款流行的JavaScript模板引擎
摘要:Javascript模板引擎作为数据与界面分离工作中最重要一环,受到开发者广泛关注.本文通过开发实例解析五款流行模板引擎:Mustache.Underscore Templates.Embedd ...
- Micro Templating源码分析
关于模板,写页面的人们其实一直在用,asp.net , jsp , php, nodejs等等都有他的存在,当然那是服务端的模板. 前端模板,作为前端人员肯定是多少有接触的,Handlebars.js ...
- [转] 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 ...
- Javascript模版引擎简介
回顾 Micro-Templating 出自John Resig 2008年的一片文章,以及其经典实现: // Simple JavaScript Templating // John Resig - ...
- JavaScript模板引擎使用
1. [代码]tmpl.js // Simple JavaScript Templating// John Resig - http://ejohn.org/ - MIT Licensed(f ...
随机推荐
- 25.C++- 泛型编程之函数模板(详解)
本章学习: 1)初探函数模板 2)深入理解函数模板 3)多参函数模板 4)重载函数和函数模板 当我们想写个Swap()交换函数时,通常这样写: void Swap(int& a, int&am ...
- SpringCloud的服务注册中心(三) - 进一步了解 Eureka
一.服务治理参与者 服务注册中心: eureka-server 服务提供者:HELLO-SERVICE 服务消费者 :HELLO-CONSUMER 很多时候,客户端既是服务提供者又是服务消费者,-&g ...
- leetcode算法: Find Largest Value in Each Tree Row
'''You need to find the largest value in each row of a binary tree.Example:Input: 1 / \ 3 2 / \ \ 5 ...
- fetch简明学习
前面的话 Fetch API 提供了一个 JavaScript接口,用于访问和操纵HTTP管道的部分,例如请求和响应.它还提供了一个全局 fetch()方法,该方法提供了一种简单,合乎逻辑的方式来跨网 ...
- jQuery ajax方法success()中后台传来的四种数据类型
1.后台返回一个页面 js代码 /**(1)用$("#content-wrapper").html(data);显示页面*/ $.ajax({ async : false, cac ...
- POJ-3617 Best Cow Line---字符串贪心
题目链接: https://vjudge.net/problem/POJ-3617 题目大意: 每次都可以从字符串的首部或者尾部提取字母,使得最后的字符串的字典序最小. 思路: 贪心做即可~每次从上和 ...
- 关于terraform的状态管理
我们想在aws创建3台主机,使用ansible和terraform都是可以实现的. 用ansible可能是这样子的: - ec2: count: 10 image: ami-40d281120 ins ...
- 关于if后面直接加上参数名,不加条件的用法
<template> <section> <p v-if="aa">{{aa}}</p> <p v-if="bb&q ...
- win10安装Ubuntu14.04双系统
1 制作镜像 UltralISO刻录镜像到U盘,下载地址:http://pan.baidu.com/s/1o7JpthS 2压缩空间给Ubuntu安装 使用windows自带的压缩(磁盘管理) 3安装 ...
- getgpc($k, $t='GP'),怎么返回的是 NULL?
<?php /** * 实用小代码 * 获得GET POST COOKIS */ $html=<<<WORD <form method="post"& ...