#StackBounty: #javascript #jquery #handlebars.js Handlebars – calculation based on array key within a template

Bounty: 50

I’m new to Handlebars and using version 4.1.2. I’m trying to move some templates which were written in PHP to Handlebars.

The source of my data is a JSON feed and the structure is like this:

[
    {
        "regulations_label": "Europe",
        "groups_label": "Group 1",
        "filters_label: "FF1A"
    },
    {
        "regulations_label": "Europe",
        "groups_label": "Group 1",
        "filters_label: "FF1B"
    },
    {
        "regulations_label": "Europe",
        "groups_label": "Group 2",
        "filters_label: "FF2A"
    },
    {
        "regulations_label": "Asia",
        "groups_label": "Group 999",
        "filters_label: "FF999A"
    },
    {
        "regulations_label": "Asia",
        "groups_label": "Group 999",
        "filters_label: "FF999B"
    },
    {
        "regulations_label": "Americas",
        "groups_label": "Group 10000",
        "filters_label: "FF10000A"
    },
]

The output of my HTML template (in the PHP version) was as follows:

  • Europe
    • Group 1
      • FF1A
      • FF1B
    • Group 2
      • FF2A
  • Asia
    • Group 999
      • FF999A
      • FF999B
  • Americas
    • Group 10000
      • FF10000A

The way in which this was achieved – without duplicating any of the regulations_label or groups_label during output – was to use conditional logic which checked the previous array value to see if it had changed, e.g.

// $data is the JSON above. 
foreach ($data as $key => $d): 
    if ($data[$key-1]['groups_label'] !== $d['groups_label'])
        echo $d['groups_label'];
    endif;
endforeach;

The above code means that groups_label is only rendered if it is not the same as the previous value, i.e. it can only print “Group 1” once, etc.

So in Handlebars I’m wanting to apply the same principle. I’ve read Handlebars/Mustache – Is there a built in way to loop through the properties of an object? and understand there is a {{@index}} and {{@key}}.

The problem I’m having is that I can’t apply conditional logic on these. For example there is no such thing as {{@index - 1}}.

The way in which I have it set up is as follows:


    {{#each myregs}}
        - {{regulations_label}} 
-- {{groups_label}}
---- {{filters_label}}
{{/each}} var regsInfo = $('#regulations-template').html(); var template = Handlebars.compile(regsInfo); var regsData = template({ myregs: // JSON data shown above }); $('#output').html(regsData);

The content is rendered to the #output div, but it repeats each level, e.g.

- Europe
    -- Group 1
        ---- FF1A
- Europe
    -- Group 1
        ---- FF1B

This problem is only happening because I’m unable to find a way to see what the previous array value was and do conditional logic. How can I solve this problem?


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.