迷你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 ...
随机推荐
- 静态Web开发 CSS
二章 CSS 1节CSS介绍 CSS(Cascading Style Sheets) //cascade级联,串联CSS由两个部分组成:选择器,以及一条或多条声明selector{declaratio ...
- jdk 1.5新特性说明
“JDK1.5”的一个重要主题就是通过新增一些特性来简化开发,这些特性包括泛型,for-each循环,自动装包/拆包,枚举,可变参数,静态导入.使用这些特性有助于我们编写更加清晰,精悍,安全的代码. ...
- 《深入Java虚拟机学习笔记》- 第3章 安全
3.1为什么需要安全性 Java的安全模型是其多个重要结构特点之一,它使Java成为适于网络环境的技术.因为网络提供了一条攻击连人的计算机的潜在途径,因此安全性是非常重要的.Java安全模型侧重于保护 ...
- vi中如何去除高亮显示的单词
在vi命令行模式下输入:set nohlsearch 单词不高亮显示:set hlsearch 单词高亮显示: 如果再次打开仍然显示,则可以随便搜索一个不存在的单词,然后保存,重新打开高亮不在显示:
- C#编写 "Hello,Word!" 您的第一个程序。
教程 下面的示例展示编写C#“Hello World”程序的几种不同的方法. 示例 1 //Hello1.cs public class Hello1 { public static void Mai ...
- httpServer V1
package cn.edu.sss.httpServer; import java.io.BufferedReader; import java.io.IOException; import jav ...
- ubuntu安装和卸载软件命令
ubuntu安装和卸载软件命令 Ubuntu软件安装与删除相关命令 安装软件 命令: apt-get install softname1 softname2 softname3…… 卸载软件 命令: ...
- 【暑假】[深入动态规划]UVa 10618 The Bookcase
UVa 12099 The Bookcase 题目: http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=42067 思路: ...
- DP——最优三角形剖分
[动态规划]凸多边形最优三角剖分 枚举三角行,再递归三角形旁边的两个多边形.
- 关于使用digitalocean的vps
先说说测试速度 平均在延迟125ms,机房选择新加坡 还有其他机房,比如伦敦,西海岸,阿姆斯特丹,基本全球覆盖. 以前用linode,virpus. linode以前有$5的套餐,现在最低都在10刀了 ...