Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing Handlebars #each helper with no key in JSON
    text
    copied!<p>I am using a PHP file to pull data from a database and return it as JSON. I want to then use the JSON data as the context for a Handlebars template. My problem is that I can't seem to get Handlebars' "{{#each}}" helper to work with the JSON being returned by the PHP file.</p> <p>Here is an example of the JSON that is returned:</p> <pre><code>[ { "id": "3", "type": "Abseiling", "title": "Abseiling Adventure", "location": "Glenrock State Conservation Area", "date": "2012-12-18 00:00:00", "length": "2 hours", "price": "50" }, { "id": "1", "type": "Abseiling", "title": null, "location": "Glenrock State Conservation Area", "date": "2013-02-10 00:00:00", "length": "3 hours", "price": "70" } ] </code></pre> <p>Here is my Handlebars template:</p> <pre><code>{{#each}} &lt;p&gt;{{location}}&lt;/p&gt; {{/each}} </code></pre> <p>I have also tried:</p> <pre><code>{{#each}} &lt;p&gt;{{this.location}}&lt;/p&gt; {{/each}} </code></pre> <p>My suspicion as to why this isn't working is that the #each helper cannot be run like I'm trying, but rather has to be called like so: {{#each something}}. If this is the case, is there any easy way to add a key to the JSON data so that it is in this form:</p> <pre><code>something: [ { ... }, { ... } ] </code></pre> <p>If my suspicion is wrong, how can I use the #each helper with the JSON I'm currently providing as the template context?</p> <p><strong>UPDATE:</strong> Found a solution for this problem, I simply had to change the template call from</p> <pre><code>jQuery(".events").html(Handlebars.templates['Events'](data)); </code></pre> <p>to</p> <pre><code>jQuery(".events").html(Handlebars.templates['Events']({events: data})); </code></pre> <p>Which meant I could then use {{#each events}}.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload