Reputation: 419
I am using the handlebars lookup helper to lookup an object in an array based on the index.
Unfortunatelly I do not manage to output a property of the object.
HTML:
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>Employees</h1>
<div class="body">
<ul>
<li> 1.Employee {{lookup this 0}}</li>
<li> 2.Employee {{lookup this 1}}</li>
</ul>
</div>
</div>
</script>
<div id="content">
</div>
Javascript:
var employees = [ { name : 'Joe'}, { name : 'Bob'} ];
var source = $("#entry-template").html();
var template = Handlebars.compile(source);
var html = template(employees);
$('#content').append(html);
and jsfiddle: https://jsfiddle.net/sgu2mmdz/1/
This is a simplified example to demonstrate my problem. I am aware that there are simplier ways so output the name by using the each helper
Edit: This is an updated jsfiddle with a version, which is closer to what I need to achieve: https://jsfiddle.net/sgu2mmdz/6/
Upvotes: 1
Views: 1360
Reputation: 14561
You could access the array objects directly with this.<index>.<property>
. So in your case it would be something like this.0.name
to get the name from the first element in the employees array. Here's the updated fiddle: https://jsfiddle.net/sgu2mmdz/3/
I hope this is what you want. Of course, as you mention in the question, it can also be done using each
.
Also, I would suggest that you use log
to debug such issues. It can often help you identify what you are doing wrong.
var employees = [ { name : 'Joe'}, { name : 'Bob'} ];
var source = $("#entry-template").html();
var template = Handlebars.compile(source);
var html = template(employees);
$('#content').append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.10/handlebars.js"></script>
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>Employees</h1>
<div class="body">
<ul>
<li> 1.Employee {{this.0.name}}</li>
<li> 2.Employee {{this.1.name}}</li>
</ul>
</div>
</div>
</script>
<div id="content">
</div>
Upvotes: 1