Kristian
Kristian

Reputation: 21830

Handlebars Reference two separate objects in the same line

I have a lookup object called Locations:

{
  'CA:' 'California',
  'NV': 'Nevada',
  'FL': 'Florida',
  ...
}

and an array of addresses:

[
  {street:'123 place', state:'FL', ...}
]

Is it possible to reference the output of a lookup in a handlebars template tag?

Something like this is what I've tried

{{#each addresses}}
  {{Lookup[this.state]}}
{{/each}}

But I get an error. So i'm probably referencing Lookup wrong.

Upvotes: 0

Views: 216

Answers (1)

Jordan Running
Jordan Running

Reputation: 106067

The lookup helper, in addition to being lower-case (not "Lookup"), takes two arguments separated by spaces. The first argument is the path to the object (or array) you want to do the lookup in and the second argument is the key to use. So in your case you probably want {{lookup ../locations this.state}}. Here it is in a snippet:

var source =
  '{{#each addresses}}' +
    '<li>{{lookup ../locations this.state}}</li>' +
  '{{/each}}';

var template = Handlebars.compile(source);

var data = {
  locations: {
    'CA': 'California',
    'NV': 'Nevada',
    'FL': 'Florida',
    // ...
  },
  addresses: [
    { street: '123 Place', state: 'FL' },
    { street: '456 Other', state: 'NV' },
    { street: '789 Last', state: 'CA' },
    // ...
  ]
};

document.getElementById('list').innerHTML = template(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.4/handlebars.js"></script>
<ul id="list"/>

Upvotes: 1

Related Questions