helpers / handlebars-helpers

188 handlebars helpers in ~20 categories. Can be used with Assemble, Ghost, YUI, express.js etc.
http://assemble.io/helpers/
MIT License
2.22k stars 364 forks source link

Accessing nested property from {{first}} and {{last}} #312

Closed Mika571 closed 6 years ago

Mika571 commented 6 years ago

I can't figure out how to access the nested property on an array using the first and last helpers. I have an array,

"test" : [{
        "a" : 1,
        "b" : 2
    },
    {
        "a" : 2,
        "b" : 3
    }]

I have tried using array syntax {{{{last test}}.0.a}} but no luck.

A7bert commented 6 years ago

{{#each test}} {{@index1}}

{{#if @last / @first }} ... {{/if}} {{/each}

Does this work for you? If I understand your question correctly.

Mika571 commented 6 years ago

Could you explain the {{#if @last / @FIRST }} statement?

Is there anyway of doing it directly using the {{first}} or {{last}} helpers?

A7bert commented 6 years ago

That statement is from my snippet, for first or last item, use @last or @first. Sorry for the confusion.

You could write your own helpers without @

doowb commented 6 years ago

@Mika571 because of how handlebars works, you'll have to use either the built-in lookup helper or make your own helper that will access what you want...

The first and last helpers take an array and return either the first or last item in the array. Since your array has objects, the value will be an object which can be passed into the lookup helper using subexpressions:

{{lookup (first test) "a"}}
{{lookup (last test) "a"}}

@A7bert what you're referring to features of the each that would be used if you're iterating over the entire array. In that case, the lookup helper would still need to be used:

{{#each test as |item|}}
  {{#if @first}}{{lookup item "a"}}{{/if}}
  {{#if @last}}{{lookup item "b"}}{{/if}}
{{/each}}