Last active
August 29, 2015 13:56
-
-
Save holyzfy/9272555 to your computer and use it in GitHub Desktop.
模板引擎
This file contains 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
/** | |
* 模板引擎 | |
* | |
* @param {String} template 模板,占位符默认是{} | |
* @param {Object} data 数据 | |
* @param {RegExp} regexp 用正则自定义占位符 | |
* return {String} | |
*/ | |
function render(template, data, regexp) { | |
if (!(Object.prototype.toString.call(data) === "[object Array]")) { | |
data = [data] | |
} | |
var ret = []; | |
for (var i = 0, length = data.length; i < length; i++) { | |
ret.push(replaceAction(data[i])); | |
} | |
return ret.join(""); | |
function replaceAction(object) { | |
return template.replace(regexp || (/\\?\{([^}]+)\}/g), function (match, name) { | |
if (match.charAt(0) == '\\') | |
return match.slice(1); | |
return (object[name] != undefined) ? object[name] : ''; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment