Skip to content

Instantly share code, notes, and snippets.

@manxisuo
Created December 9, 2013 16:37
Show Gist options
  • Select an option

  • Save manxisuo/7875436 to your computer and use it in GitHub Desktop.

Select an option

Save manxisuo/7875436 to your computer and use it in GitHub Desktop.
12行代码实现简易Javascript模板引擎
;(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';
* });
* }
*/
// 示例
;(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