Skip to content

Instantly share code, notes, and snippets.

@holyzfy
Last active August 29, 2015 13:56
Show Gist options
  • Save holyzfy/9272555 to your computer and use it in GitHub Desktop.
Save holyzfy/9272555 to your computer and use it in GitHub Desktop.
模板引擎
/**
* 模板引擎
*
* @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