0

I can't seem to find a way of doing this, and have tried subexpressions and various other answers posted on StackOverflow - but they all seem to assume that I know the key I'm using in advance.

I have the following object:

{
    fields: {
        1: {
            complete: 1,
            submitted: 0
        },
        2: {
            complete: 1,
            submitted: 0
        }
}

etc. etc.

In my Handlebars template, I'm looping through an array of objects. Each object in that array has a field_id key which is a number that matches up to the 1 or 2 in the above example.

I need to access the variables in the above array structure, based on the current field_id being looped. I've tried:

{{fields[(field_id)].complete}}

{{fields[{{field_id}}].complete}}

{{fields.(field_id).complete}}

{{fields.({{field_id}}).complete}}

And none of them work.

Is there a way of doing this?

1
  • Where does field_id come from? Commented Sep 3, 2016 at 20:23

2 Answers 2

1

I would not create a custom helper for this. Instead, I would use the existing Lookup helper partnered with the with block helper:

{{#with (lookup fields field_id) as |field|}}
    {{field.complete}}
{{/with}}

Alternatively you could use the lookup helper with a subexpression:

{{lookup (lookup fields field_id) 'complete'}}
Sign up to request clarification or add additional context in comments.

1 Comment

I used the latter solution here, much neater than my custom helper. Thank you muchly!
0

I made this work by registering a custom helper:

Handlebars.registerHelper( 'getfield', function ( data, field_id, key ) {
    var val = ( data[ field_id ] ) ? data[ field_id ][ key ] : '';
    return val;
} );

and then made use of this in my templates with:

{{getfield fields field_id 'complete'}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.