I'm getting to know Handlebars.js and I would have a question for the community. I know I have a lot more to learn and I'm on my way, but I'd like to see an example to this problem.
The array created in JS with the objects:
var data =
[
{
Field: "id",
Type: "int(11)",
Null: "NO",
Key: "PRI",
Default: null,
Extra: "auto_increment"
},
{
Field: "id2",
Type: "int(131)",
Null: "N3O",
Key: "PR3I",
Default: null,
Extra: "auto_increment"
}
];
The format is this because the JSON I receive from the server will look like the exact way, but now for testing I didn't want to make an ajax call.
The template:
<table>
<thead>
<tr>
{{#each this}}
{{#only_once this}}
{{#key_value this}}
<th>{{key}}</th>
{{/key_value }}
{{/only_once}}
{{/each}}
</tr>
</thead>
...
Because the objects are in an array, I have to loop firstly the array with {{#each}}
then there comes a registered helper (I found on github) that help me get the key because I want to write only them to the thead.
Without my if statement it works fine, fill in the thead with the keys, but because there are 2 objects, it prints out the names twice.
My problem is that I want to print them only once and an if would solve my problem that checks if the index of the array is greater than 0 to stop printing out the data, but..
.. Handlebars doesn’t support conditional statements, so code like {{#if x > y}}
isn’t possible. What do you guys think would be the best solution for it?
Handlebars.registerHelper("only_once", function(item, fn){
var buffer;
var i = 0;
if (i > 0) {
buffer = false;
}
i++;
return buffer;
});
Well, I tried to write a helper, but I think I did something wrong. My theory was that I give to my if the 'this
' in the template as it (I think) points back to the array and then increase the i
to check if the index of the array is > than 0, finally if it's true than send back a false - so I thought it will say to the if that don't run the code inside, but I though wrongly.