Created
December 3, 2013 09:40
-
-
Save siongui/7766638 to your computer and use it in GitHub Desktop.
Simple JavaScript Template Engine in 12 lines. From:
http://www.oschina.net/code/snippet_919901_26970
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
有时候在使用javascript的时候需要格式化一些输出,比如AJAx回来的JSON数据格式化成HTML片段的时候,使用简单的字符串拼接都闲得比较麻烦,当然有的时候可以使用一些JS模板引擎但是又觉得不合适,可能代码里就只用到了几处这样的功能却引入及时KB的JS库,有些不划算。这里给出一个只要12行代码就可以实现的模板引擎。功能很简单只是替换变量。但是对于一般的需求应该是够用了。 | |
*/ | |
;(function (window) { | |
function Template(str) { | |
this.str = str; | |
} | |
Template.prototype.format = function () { | |
var arg = arguments[0] instanceof Array ? arguments[0] : arguments; | |
return this.str.replace(/\{(\d+)\}/g, function (a, b) { | |
return arg[b] || ''; | |
}); | |
} | |
window.Template = Template; | |
})(window); | |
/** | |
* 说明: 这里主要用到了JS里String.prototype.replace函数支持正则和回调函数的功能。 | |
* 所以大家有自己的需求是很容易修改的。只要替换下上面的正则和回调函数就可以了。 | |
* 如果是JSON数据的话可以修改成这样的: | |
* Template.prototype.format = function (o) { | |
* return this.str.replace(/\{(\w+)\}/g, function (a, b) { | |
* return o.hasOwnProperty(b) ? : o[b] : 'null'; | |
* }); | |
* } | |
*/ | |
// Usage: | |
;(function(){ | |
/** 这个JS模板引擎只适用于数据哈 */ | |
var t = new Template('<p><a href="{0}">{1}</a><span>{2}</span></p>'); | |
var s = t.format('http://www.google.com', 'Google', 'Google搜索引擎'); | |
var s = t.format(['http://www.google.com', 'Google', 'Google搜索引擎']); // 和上面一行代码的功能是一样的 | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment