Last active
December 22, 2015 08:48
-
-
Save nightink/6447175 to your computer and use it in GitHub Desktop.
handlebars.js -- Uncertain number of attributes object traversal
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
/** | |
* handlebars eachObj | |
* User: Nightink | |
* Date: 13-08-23 | |
*/ | |
define(function(require, exports, module) { | |
var handlebars = require('handlebars'); | |
function isFunction(value) { | |
return Object.prototype.toString.call(value) === '[object Function]'; | |
} | |
/** | |
* count = null; The default is null iterate through all properties. | |
* var obj = {name: '', age: ''}; | |
* {{#eachObj obj count}} | |
* <tr> | |
* <td>properties:{{prop}}</td> | |
* <td>value:{{val}}</td> | |
* </tr> | |
* {{/each}} | |
*/ | |
handlebars.registerHelper('eachObj', function(obj, count, options) { | |
// options.fn is handlebars.js template parsing and generating function parameter substitution. | |
var html = [], i = 0; | |
if(isFunction(count)) { | |
options = count; | |
count = 0; | |
} | |
for(var key in obj) { | |
if(count && i >= count) { | |
break; | |
} | |
html.push(options.fn({ | |
prop: key, | |
val: obj[key] | |
})); | |
i++; | |
} | |
return html.join(''); | |
}); | |
}); | |
// var options = { | |
// fn: [function], // 模板解析生成函数 | |
// inverse: [function] | |
// }; | |
// obj 是模板需要解析的对象 options 为handlebars自身对模板的解析函数和关于的配置参数 | |
// 对性能有一定的提升 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment