mercredi 4 mars 2015

Getting sibling JSON data with Handlebars, where a single object has no parent index key, but multiple items have an index key?

I've come across an interesting, but annoying situation with some data i'm grabbing from an API that sort of exposes the downfalls of using a templating language like Handlebars. (Helpers, Helpers everywhere!)


Is there a clean way to handle the following situation. Essentially, if a JSON object only has only has one sibling, it's not wrapped with a key, but if it returns multiple, they're wrapped with a key.


So below we have an example where ingredient has one sibling, and it's returned without being wrapped. The second object returns 2 ingredients, and so they're wrapped with an index key.


I can't really do anything about the way the data looks, i've just got to be able to handle it.


I'm assuming a helper is the way to go, but i'm hoping there's a neat trick for handling the following situation in order to catch both depending on what data is returned. I'd also prefer to do it using pure Handlbars if possible (without the help of Ember etc).


If anyone can help, i'd appreciate it!


Scenario 1: "food":{ "ingredient":{ "name":"Cucumber", "weight":"5", "cost":"1", } }


Scenario 2: "food":{ "ingredient":{ "1":{ "name":"Cheese", "weight":"10", "cost":"2" }, "2":{ "name":"Tomato", "weight":"20", "cost":"0.5" } } }





Aucun commentaire:

Enregistrer un commentaire