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}}
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}}
Bootstrap columns wrap automatically after 12 columns. The problem is we lose the bottom margin of the row.
While the answer you provided might work, its awfully complex.
An alternative, much simpler solution would have been to add a bottom margin to the columns.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.