2

I want to fetch the last item of my JSON file. So I took a look at Getting the last element from a JSON array in a Handlebars template and tried to implement it. So far it gives me the number of the last entry but I need the options as well but dont know how to do it?

This is from the example mentioned

Handlebars.registerHelper("last", function(array, options) {
    return array[array.length-1];
});

I tried to do:

Handlebars.registerHelper("last", function(array, options) {
    if (array[array.length-1]) return options.fn(this);
    return options.inverse(this);
});

My JSON files structure is:

releases: [{
    "title" : "some title",
    "releaseDate" : "2014-08-04"
    },
    "services": [{
         "name" : "spotify",
         "link" : "some link"
     }, 
     {
         "name" : "itunes",
         "link" : "some link"
    }]
  ]

so my Handlebars template looks like:

{{#each releases}}
    {{#last releaseDate}}
        {{#each services}}
            {{#equal name "Spotify" }}
                <a href="{{link}}"></a>
            {{/equal}}
            {{#equal name "Itunes" }}
                <a href="{{link}}"></a>
            {{/equal}}
        {{/each}}
    {{/last}}
{{/each}}

But its not working, it displays an empty DIV

please help?

Community
  • 1
  • 1
SHT
  • 700
  • 4
  • 18
  • 39

2 Answers2

8

Handlebars already has @first and @last pseudo-variables. See docs on iterations and built-in helpers.

Example use case:

textArray = ["First", "N-1", "Last"]

<span>{{#each textArray}}{{#if @last}}{{this}}{{/if}}{{/each}}</span>

Result: <span>Last</span>

Will
  • 383
  • 3
  • 12
raidendev
  • 2,729
  • 1
  • 22
  • 23
0

I would use an iterator helper for this.

Handlebars.registerHelper('layoutReleases', function (rows, options) {
    var buffer = [], lastRow;
    if (rows && rows.length > 0) {
        lastRow = rows[rows.length-1];
        buffer.push(options.fn(lastRow));
    }
    return buffer.join('');
});

Template:

{{#layoutReleases releases}}
    {{releaseDate}}
    {{#each services}}
       {{#equal name "Spotify" }}
            <a href="{{link}}"></a>
       {{/equal}}
       {{#equal name "Itunes" }}
            <a href="{{link}}"></a>
       {{/equal}}
    {{/each}}
{{/each}}
Fix It Scotty
  • 2,852
  • 11
  • 12