//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. spring data jpa入门学习

    本文主要介绍下spring data jpa,主要聊聊为何要使用它进行开发以及它的基本使用.本文主要是入门介绍,并在最后会留下完整的demo供读者进行下载,从而了解并且开始使用spring data ...

  2. UVA 11082 Matrix Decompressing 矩阵解压(最大流,经典)

    题意: 知道矩阵的前i行之和,和前j列之和(任意i和j都可以).求这个矩阵.每个格子中的元素必须在1~20之间.矩阵大小上限20*20. 思路: 这么也想不到用网络流解决,这个模型很不错.假设这个矩阵 ...

  3. 【转】Effective-Objective-C-读书笔记-Item-4-如何正确定义常量 -- 不错

    原文网址:http://tutuge.me/2015/03/11/Effective-Objective-C-%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0-Item-4-% ...

  4. c#保存datagridview中的数据时报错 “动态SQL生成失败。找不到关键信息”

    ilovejinglei 原文 C#中保存datagridview中的数据时报错"动态SQL生成失败.找不到关键信息" 问题描述     相关代码 using System; us ...

  5. Win10 查看IE的临时目录

    C:\Users\YOUR_NAME\AppData\Local\Microsoft\Windows\INetCache

  6. MyEclipse2014安装ADT插件(适用于其他版本)

    这次,本文采用公认的最佳插件安装方式——link方式来安装ADT插件,此方法适用于Eclipse以及MyEclipse其他版本.下面为大家一一道来: 大致过程如下: 官方的在线安装很麻烦,找了很久,终 ...

  7. HDU 1560 DNA sequence DFS

    题意:找到一个最短的串,使得所有给出的串是它的子序列,输出最短的串的长度,然后发现这个串最长是40 分析:从所给串的最长长度开始枚举,然后对于每个长度,暴力深搜,枚举当前位是哪一个字母,注意剪枝 注: ...

  8. setup.s

    INITSEG = 0x9000 ! we move boot here - out of the way ! 原来 bootsect 所处的段. ! ok, the read went well s ...

  9. HDFS的shell操作

    bin/hadoop命令操作: namenode -format 格式化文件系统 fs(缩写:FileSystem) 运行一个文件系统的用户客户端 bin/hadoop fs常用命令操作: -ls h ...

  10. eclipse下使用tomcat启动maven项目

    最近学习使用maven,建立了一个maven项目使用eclipse下tomcat启动时报错: 严重: ContainerBase.addChild: start: org.apache.catalin ...