迷你template
JavaScript Micro-Templating
http://ejohn.org/blog/javascript-micro-templating/

//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>
来个完整的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta name="format-detection" content="telephone=no" />
<title>news</title>
<link rel="stylesheet" type="text/css" href="./css/css.css" media="screen" />
</head>
<body>
<div id="container">
<section class="news layout" id="newsList">
<figure class="clr big-img">
<a href="http://www.baidu.com">
<figcaption>疯狂世界杯,挖财社区邀您High!</figcaption>
<span class="img"><img src="./image/0.jpg" alt="" width="100%"></span>
<span class="time">15分钟前</span>
</a>
</figure>
<figure class="clr small-img hot">
<a href="http://www.baidu.com">
<img src="./image/1.jpg" class="fr mgl15" alt="" width="80">
<figcaption>什么叫拿奖拿到手抽筋,你造吗?</figcaption>
<span class="time">30分钟前</span>
</a>
</figure>
<figure class="clr small-img">
<a href="#">
<img src="./image/2.jpg" class="fr mgl15" alt="" width="80">
<figcaption>问题来了:半年结余了11万存款该怎么用</figcaption>
<span class="time">41分钟前</span>
</a>
</figure>
<figure class="clr">
<a href="#">
<figcaption>版主倾囊相授:行业从业者教你认清保险背后的事情 </figcaption>
<span class="time">1小时前</span>
</a>
</figure>
</section>
</div>
<script>
// 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;
};
})();
</script>
<script type="text/html" id="big_img">
<figure class="clr big-img [%=(recommend ? "hot" : "")%]">
<a href="[%=url%]">
<figcaption>[%=content%]</figcaption>
<span class="img" data-url="[%=imgSrc%]">点击加载图片</span>
<span class="time">[%=time%]</span>
</a>
</figure>
</script>
<script type="text/html" id="small_img">
<figure class="clr small-img [%=(recommend ? "hot" : "")%]">
<a href="[%=url%]">
<img src="[%=imgSrc%]" class="fr mgl15" alt="" width="80" height="60">
<figcaption>[%=content%]</figcaption>
<span class="time">[%=time%]</span>
</a>
</figure>
</script>
<script type="text/html" id="no_img">
<figure class="clr [%=(recommend ? "hot" : "")%]">
<a href="[%=url%]">
<figcaption>[%=content%]</figcaption>
<span class="time">[%=time%]</span>
</a>
</figure>
</script>
<script>
var list = [{
recommend: 1,
content: "我来测试测试",
url: "http://www.baidu.com",
imgSrc: "http://h.hiphotos.baidu.com/image/pic/item/b17eca8065380cd7ce039fe4a344ad345982819d.jpg",
time: "15分钟前"
}, {
recommend: 0,
content: "我来测试测试",
url: "http://www.baidu.com",
imgSrc: "http://h.hiphotos.baidu.com/image/pic/item/b17eca8065380cd7ce039fe4a344ad345982819d.jpg",
time: "20分钟前"
}
]; var oDiv = document.getElementById("newsList"),
len = list.length,
i = 0,
html = ""; for(; i < len; i++) {
html += tmpl("small_img", list[i]);
} oDiv.innerHTML = html;
</script>
</body>
</html>
迷你template的更多相关文章
- 不可错过的javascript迷你库
最近看着下自己的github star,把我吓坏了,手贱党,收藏癖的我都收藏了300+个仓库了,是时候整理一下了. Unix主张kiss,小而美被实践是最好用的,本文将介绍笔者收集的一些非常赞的开源库 ...
- 写一个迷你版Smarty模板引擎,对认识模板引擎原理非常好(附代码)
前些时间在看创智博客韩顺平的Smarty模板引擎教程,再结合自己跟李炎恢第二季开发中CMS系统写的tpl模板引擎.今天就写一个迷你版的Smarty引擎,虽然说我并没有深入分析过Smarty的源码,但是 ...
- 我是这样使用template.js来异步渲染数据的
总监的代码用的是define+module.exports,为了效率先没去了解那一块,在github上找了一款功能单一的template.js来使用 https://github.com/yanhai ...
- DiscuzX2.5,X3.0,X3.1,X3.2完整目录结构【模板目录template】
/template/default/common 公共模板目录全局加载 block_forumtree.htm DIY论坛树形列表模块 block_thread.htm DIY帖子模块调用文件 ...
- 迷你MVVM框架 avalonjs 1.3.6发布
本版本是一次重要的升级,考虑要介绍许多东西,也有许多东西对大家有用,也发到首页上来了. 本来是没有1.36的,先把基于静态收集依赖的1.4设计出来后,发现改动太多,为了平缓升级起见,才减少了一部分新特 ...
- 60行代码实现一个迷你版Vue Router
这是一个超级精简版的VueRouter,实现hash模式下,hash改变组件切换的功能,原理就是利用了 Vue.js 的响应式机制触发router-view组件的重新渲染. 代码 https://gi ...
- 为.NET Core项目定义Item Template
作为这个星球上最强大的IDE,Visual Studio不仅仅提供了很多原生的特性,更重要的是它是一个可定制的IDE,比如自定义Project Template和Item Template就是一个非常 ...
- jQuery.template.js 简单使用
之前看了一篇文章<我们为什么要尝试前后端分离>,深有同感,并有了下面的评论: 我最近也和前端同事在讨论这个问题,比如有时候前端写好页面给后端了,然后后端把这些页面拆分成很多的 views, ...
- 2000条你应知的WPF小姿势 基础篇<69-73 WPF Freeze机制和Template>
在正文开始之前需要介绍一个人:Sean Sexton. 来自明尼苏达双城的软件工程师.最为出色的是他维护了两个博客:2,000ThingsYou Should Know About C# 和 2,00 ...
随机推荐
- java高并发,如何解决,什么方式解决
之前我将高并发的解决方法误认为是线程或者是队列可以解决,因为高并发的时候是有很多用户在访问,导致出现系统数据不正确.丢失数据现象,所以想到 的是用队列解决,其实队列解决的方式也可以处理,比如我们在竞拍 ...
- Linux kernel Makefile for ctags
/********************************************************************** * Linux kernel Makefile for ...
- 学习xcode 博客
csdn http://blog.csdn.net/tianyitianyi1/article/category/1160169/2
- lightoj 1224
很简单的Trie树,记录每个前缀的次数,dfs一次Trie即可 #include<set> #include<map> #include<list> #includ ...
- [selenium webdriver Java]检查元素是否存在
Selenium WebDriver没有实现Selenium RC的isElementPresent()方法来检查页面上的元素是否存在. 在WebDriver中封装一个类似的方法,如下: public ...
- Jmeter初步使用--Jmeter安装与使用
由于jmeter是开源的性能测试工具,但是使用的人较少,网络上相关资料不全面,需要自己去揣摩,因此,小编就把自己在用Jmeter时的一些小结总结出来.而loadrunner工具是商业软件,网上通常都是 ...
- selenium+testNG+Ant
好几天没写了,抽时间写下,也好有个总结: 1.selenium+testNG+Ant (1)ant 是构建工具 他的作用就是运行你配置好的东西 而tentng.xml你可以认为他是管理test的一个配 ...
- Linux Add a Swap File
http://www.cyberciti.biz/faq/linux-add-a-swap-file-howto/ Procedure To Add a Swap File Under Linux Y ...
- dateline 在数据库中就是 整型字段。date函数是可以转换成可读日期的。
返回数据中的dateline全部用date()函数转换后再返回,是要嵌套循环还是遍历,代码怎么写? //查询我的活动 function user_activity_info_by_uid($uid){ ...
- BNUOJ-29365 Join in tasks 简单数学
题目链接:http://www.bnuoj.com/bnuoj/problem_show.php?pid=29365 首先排序,然后维护一个后缀,等差求下和就可以了.. //STATUS:C++_AC ...