I believe I'm needing a custom Handlebars.js Block Helper to handle rows inside a Bootstrap based grid system. I'd like every 3 items to be wrapped in <div class="row"></div>
<div class="row">
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
</div>
{{#employees}}
<div class="col-sm-4">
<strong>{{name}}</strong><br>
{{title}}<br>
{{skills}}
</div>
{{/employees}}
var data = {
"employees" : [
{
"name":"Fred Flintstone",
"title":"Frontend Developer",
"skills" : "html,css,javascript"
},
{
"name":"Sally Struthers",
"title":"Frontend Developer",
"skills" : "html,css,javascript"
},
{
"name":"Ben Wilson",
"title":"Frontend Developer",
"skills" : "html,css,javascript"
},
{
"name":"Julie Milson",
"title":"Frontend Developer",
"skills" : "html,css,javascript"
},
{
"name":"Mike Barton",
"title":"Frontend Developer",
"skills" : "html,css,javascript"
}
]
}
This is what I was thinking but need help with :)
// pass data and how many per row
Handlebars.registerHelper('gridWrap', function(data,perRow) {
var wrapper = "";
// need index
if(index == 0 || index % perRow == 0) {
wrapper += '<div class="row">';
}
if((index + 1) % perRow == 0 || (index + 1) == data.length) {
wrapper += '</div>';
}
return wrapper;
});
Then once helper is constructed how would you use it in the html?
{{#employees}}
{{#gridWrap employees 3}} {{wrapper}} {{/gridWrap}}
<div class="col-sm-4">
<strong>{{name}}</strong><br>
{{title}}<br>
{{skills}}
</div>
{{#gridWrap employees 3}} {{wrapper}} {{/gridWrap}}
{{/employees}}
Here's a link to a Codepen
ok :) found the answer here in this killer post!
This helper is exactly what I was looking for. Here is what I ended up with :)
Handlebars.registerHelper('grouped_each', function(every, context, options) {
var out = "", subcontext = [], i;
if (context && context.length > 0) {
for (i = 0; i < context.length; i++) {
if (i > 0 && i % every === 0) {
out += options.fn(subcontext);
subcontext = [];
}
subcontext.push(context[i]);
}
out += options.fn(subcontext);
}
return out;
});
{{#grouped_each 3 employees}}
<div class="row">
{{#each this }}
<div class="col-sm-4 item">
<strong>{{name}}</strong><br>
{{title}}<br>
{{skills}}
</div>
{{/each}}
</div>
{{/grouped_each}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With