1

I'm trying to use the Handlebars templating engine to compile some templates from within the browser. I now build a drop down using an each loop and I want one of the options to be selected. For this I copied a helper (from this SO answer) like this:

Handlebars.registerHelper('if_eq', function(a, b, opts) {
    if(a == b)
        return opts.fn(this);
    else
        return opts.inverse(this);
});

I then supply the following object to the handlebars:

{
    "adminUsers": [
        {
            "adminUsername": "user1"
        },
        {
            "adminUsername": "user2"
        },
        {
            "adminUsername": "user3"
        }
    ],
    "assignedAdminUser": "user2"
}

And in my Handlebars template I do this:

{{#each adminUsers}}
    {{#if_eq adminUsername assignedAdminUser }}
        <option selected>{{adminUsername}}</option>
    {{else}}
        <option>{{adminUsername}}</option>
    {{/if_eq}}
{{/each}}

But unfortunately none of the options is selected. The equal helper does work when I simply fill in 'a' and 'a', but somehow the assignedAdminUser isn't available within the #each loop. I can easily echo it using {{assignedAdminUser}} outside the loop, but within it doesn't seem available.

Does anybody know how I can check whether the adminUser in the loop is equal to the assigned user so that I can set that option to selected? All tips are welcome!

Community
  • 1
  • 1
kramer65
  • 50,427
  • 120
  • 308
  • 488

1 Answers1

2

Inside your each loop, you're in the context of your adminUser object. These objects don't have an assignedAdminUser property, which is why your if_eq check is failing every time.

Use

{{#if_eq adminUsername ../assignedAdminUser}}

instead.

Timespace
  • 508
  • 4
  • 18