//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. php简单实现MVC

    在PHP中使用MVC越来越流行了,特别是在一些开源的框架当中.MVC足以应对大多数的情况,但还有一些情况是其不太适合的,如比较简单的个人博客,对于只有几百篇文章量级的博客,使用MVC让人觉得有些太复杂 ...

  2. Archlinux里面安装VMware Tools

    用虚拟机学习linux确实很方便,但是和主机的文件共享是个大问题,VMWARE TOOLS可以很好的解决这个问题,但是在ARCH里却不能向大多数linux那样方便的安装,在查了很多帖子试了无数遍之后, ...

  3. 【MySql存储过程】DATE_ADD用法

    定义和用法 DATE_ADD() 函数向日期添加指定的时间间隔. 语法 DATE_ADD(date,INTERVAL expr type) date 参数是合法的日期表达式.expr 参数是您希望添加 ...

  4. Spring depends-on介绍

    <!-- redis配置 --> <bean id="jedisPoolConfig" class="redis.clients.jedis.Jedis ...

  5. HDU 5603 the soldier of love 离线+树状数组

    这是bestcorder 67 div1 的1003 当时不会做 看了赛后官方题解,然后翻译了一下就过了,而且速度很快,膜拜官方题解.. 附上官方题解: the soldier of love 我们注 ...

  6. HW7.8

    import java.util.ArrayList; import java.util.Scanner; public class Solution { public static void mai ...

  7. Eclipse的DDMS File Explorer无法进入data目录解决方案

    进入data目录需要root权限.所以,你的手机要有root才可以.然后做以下步骤就可以了 1.cmd进入platform-tools目录 2.adb shell 3.su(这里要看手机有没有请求ro ...

  8. Android实例-消息框(XE8+小米2)

    方法一支持. 方法二与方法三都是三方单元,功能相同. 方法4与方法5报错,提示平台不支持. 第三方单元一: unit Android.JNI.Toast; // Java bridge class i ...

  9. python 安装第三方模块

    在Python中,安装第三方模块,是通过setuptools这个工具完成的. 如果你正在使用Mac或Linux,安装setuptools本身这个步骤就可以跳过了. 如果你正在使用Windows,请首先 ...

  10. [iOS基础控件 - 4.5] 猜图游戏

    A.需要掌握的 1.添加图片资源(暂时认为@2x跟非@2x代表同一张图片) 2.搭建UI界面* 文本标签* 4个按钮* 中间的图片 3.设置状态栏样式 4.监听下一题按钮的点击 5.延迟加载数据* 加 ...