的$.nano
答案扔我一個循環,因爲它錯誤,如果你在你的模板圓點符號任何錯別字,而且它不允許像a['foo bar']
所有合法字符所以下面是我的版本作爲$.substitute
插件:
/*
* JQuery Substitute method allows for simple templating using JS Object dot notation.
* Contribute link: https://gist.github.com/danielsokolowski/0954fc2a767f441720b9
*
* @param strTemplate - string contain the replacement tokens
* @param objData - an Object represetnting your replacmenet values
*
* Example:
* var strTemplate = 'Hello {user.name}'
* var strDatra = {'user': 'Daniel Sokolowski'}
* alert($.substitute(strTemplate, objData)); // outputs 'Hello Daniel Sokolowski'
*
*/
$.substitute = function(strTemplate, objData) {
return strTemplate.replace(/\{([^{}]*)\}/g, function(math, subMatch1) {
try {
var keys = subMatch1.split(".");
var value = objData[keys.shift()]; // return first element and update the original array
while (keys.length !== 0) { // keep returning properties
value = value[keys.shift()]
}
return String(value);
} catch (err) { // return any errors as a string
return String(value);
}
});
};
http://www.planabc.net/2011/05/31/simple_javascript_template_substitute/ https://github.com/yui/yui3/blob/master/src/substitute/js/substitute.js這裏是YUI的解決方案。 – 2011-11-13 05:07:06