//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的更多相关文章

  1. 不可错过的javascript迷你库

    最近看着下自己的github star,把我吓坏了,手贱党,收藏癖的我都收藏了300+个仓库了,是时候整理一下了. Unix主张kiss,小而美被实践是最好用的,本文将介绍笔者收集的一些非常赞的开源库 ...

  2. 写一个迷你版Smarty模板引擎,对认识模板引擎原理非常好(附代码)

    前些时间在看创智博客韩顺平的Smarty模板引擎教程,再结合自己跟李炎恢第二季开发中CMS系统写的tpl模板引擎.今天就写一个迷你版的Smarty引擎,虽然说我并没有深入分析过Smarty的源码,但是 ...

  3. 我是这样使用template.js来异步渲染数据的

    总监的代码用的是define+module.exports,为了效率先没去了解那一块,在github上找了一款功能单一的template.js来使用 https://github.com/yanhai ...

  4. DiscuzX2.5,X3.0,X3.1,X3.2完整目录结构【模板目录template】

    /template/default/common  公共模板目录全局加载 block_forumtree.htm  DIY论坛树形列表模块 block_thread.htm  DIY帖子模块调用文件 ...

  5. 迷你MVVM框架 avalonjs 1.3.6发布

    本版本是一次重要的升级,考虑要介绍许多东西,也有许多东西对大家有用,也发到首页上来了. 本来是没有1.36的,先把基于静态收集依赖的1.4设计出来后,发现改动太多,为了平缓升级起见,才减少了一部分新特 ...

  6. 60行代码实现一个迷你版Vue Router

    这是一个超级精简版的VueRouter,实现hash模式下,hash改变组件切换的功能,原理就是利用了 Vue.js 的响应式机制触发router-view组件的重新渲染. 代码 https://gi ...

  7. 为.NET Core项目定义Item Template

    作为这个星球上最强大的IDE,Visual Studio不仅仅提供了很多原生的特性,更重要的是它是一个可定制的IDE,比如自定义Project Template和Item Template就是一个非常 ...

  8. jQuery.template.js 简单使用

    之前看了一篇文章<我们为什么要尝试前后端分离>,深有同感,并有了下面的评论: 我最近也和前端同事在讨论这个问题,比如有时候前端写好页面给后端了,然后后端把这些页面拆分成很多的 views, ...

  9. 2000条你应知的WPF小姿势 基础篇<69-73 WPF Freeze机制和Template>

    在正文开始之前需要介绍一个人:Sean Sexton. 来自明尼苏达双城的软件工程师.最为出色的是他维护了两个博客:2,000ThingsYou Should Know About C# 和 2,00 ...

随机推荐

  1. linux mkfs命令参数及用法详解---linux格式化文件系统命令(包括swap分区)

    mkfs 命令  linux格式化磁盘命令           linux mkfs         指令:mkfs 使用权限 : 超级使用者 使用方式 : mkfs [-V] [-t fstype] ...

  2. android利用WebView实现浏览器的封装

    android提供了封装浏览器的接口,可以让开发者利用自己的view显示网页内容.今天又实现研究了一下,利用WebView显示浏览器内容,还可以利用 WebViewClient显示自己需要的内容. 参 ...

  3. 位操作:BitVector32结构 z

    目录 温习位操作 BitVector32的位操作 CreateMask方法 使用BitVector32.Section来存储小整数 BitVector32结构体位于System.Collections ...

  4. 配置Git自动补全功能

    Git装好后,默认是不会有按tab补全命令的功能的.可如下配置: 去git的源码中,找到contrib/completion/git-completion.bash 将git-completion.b ...

  5. sqlserver 2008 R2 分区表测试

    有一张表期中有100多w条数据 程序执行起来比较慢,想用分区表的办法,使查询变快一些. 方案如下 --查看分区信息SELECT * FROM sys.partition_range_values -- ...

  6. Xcode中Info.plist文件各个键的作用说明【搜藏】

    Localiztion native development region --- CFBundleDevelopmentRegion 本地化相关,如果⽤户所在地没有相应的语言资源,则用这个key的v ...

  7. MFC定时器

    比较简单,在程序中可以找到原型. 在程序中我们经常要使用定时刷新的功能,典型的应用是在信息管理系统中表单要跟着数据库中的数据变动.MFC提供了定时器来完成这个功能. ================= ...

  8. 【poj2891】Strange Way to Express Integers

    题意: 给出n个模方程x=a(mod r) 求x的最小解 题解: 这就是个线性模方程组的模版题- - 但是有一些要注意的地方 extgcd算出来的解x可能负数  要让x=(x%mo+mo)%mo 而且 ...

  9. 让浏览器进行跨域访问, 开发阶段需要跨域访问的测试方案 chrome的快捷方式里面 加 "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --args --disable-web-security

    Chrome浏览器 的快捷方式里加一个 命令可以使浏览器进行跨域访问 "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe ...

  10. php self

    self是指向类本身,也就是self是不指向任何已经实例化的对象,一般self使用来指向类中的静态变量. 假如我们使用类里面静态(一般用关键字static)的成员,我们也必须使用self来调用. 还要 ...