Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Last active January 7, 2018 09:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nathansmith/f7b94e21f03dd0bfe2c1 to your computer and use it in GitHub Desktop.
Save nathansmith/f7b94e21f03dd0bfe2c1 to your computer and use it in GitHub Desktop.
Handlebars.js helper to generate dummy UI.
/*
Handlebars helper to generate dummy UI.
For instance, a 10x10 table with 100 cells:
<table>
{{#repeat 10}}
<tr>
{{#repeat 10}}
<td>
{{@index}}
</td>
{{/repeat}}
</tr>
{{/repeat}}
</table>
*/
Handlebars.registerHelper('repeat', function(count, options) {
// Convert to number.
count = parseInt(count, 10);
// Used in loop.
var i = 0;
var arr = [];
var str;
var obj;
var first;
var last;
// Loop for count.
for (i = 0; i < count; i++) {
// Booleans for first/last.
first = i === 0;
last = i === count - 1;
/*
Allows access to magic:
- `@index`
- `@first`
- `@last`
Used in template:
{{@index}}
{{#if @first}}...{/if}
{{#if @last}}...{/if}
*/
obj = {
data: {
index: i,
first: first,
last: last
}
};
// Build the HTML.
str = options.fn({}, obj);
// Add to array.
arr.push(str);
}
// Convert to string.
var html = arr.join(' ').replace(/\s+/g, ' ');
// Trim.
if (typeof String.prototype.trim === 'function') {
html = html.trim();
}
else if (typeof jQuery === 'function') {
html = jQuery.trim(html);
}
// Send back HTML.
return html;
// END: *.registerHelper.
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment