Handlebars: Accessing nested objects with white space in the keys

Viewed 273

Here is some sample data with the structure I'm dealing with:

{ 'Employee Info':
   { 'Last Bonus Date': '1999-01-01',
     'Manager Name': 'Doe, John',
     PIN: '00000',
     'Salary Basis': 'test' }

I have managed to figure out how to access the 'Employee Info' key in the template by doing the following, using brackets with no surrounding quotes. This obviously doesn't give me anything useful other than showing Object Object in the template, but it's a start:

  <ul>
    <li>
      Manager Name: {{[Employee Info]}}
    </li>
  </ul>
  <ul>

Now what I'm trying to accomplish is pretty straight forward, I'd like to first access 'Employee Info' and then one of its values ([employee info][Manager Name]]) but no way I have tried yet seem to work. Most of the data I have to deal with has spaces in the keys. Even trying to access 'PIN' which doesn't have any spaces won't work either.

I have tried..

{{[Employee Info].pin}}

{{[Employee Info][pin]}}

{{[Employee Info].[pin]}}

1 Answers

Your issue is not due to the whitespace in your keys. As you have identified, you are able to access properties with invalid identifiers by wrapping the property name in square brackets, ex. [Employee Info].

The actual problem is that Handlebars does not permit you deep access Object properties in the form prop1.prop2. Instead, you will need to instruct Handlebars to use the Object at Employee Info as the context for your list items. One way to do this would be by using the #with built-in helper.

Your updated template would become:

<ul>
    {{#with [Employee Info]}}
        <li>Manager Name: {{[Manager Name]}}</li>
        <li>Last Bonus Date: {{[Last Bonus Date]}}</li>
        <li>PIN: {{[PIN]}}</li>
        <li>Salary Basis: {{[Salary Basis]}}</li>
    {{/with}}
<ul>

I have created a fiddle for your reference.

Related