papdel papdel - 5 months ago 19
JSON Question

Handling JSON objects with UUID keys while templating with Handlebars.js?

I have a nested JSON object which looks like this

review:{
body:{
"1cfd0269-1b8f-418f-a7b2-45eb2fa7562b": "Text1",
"38d14dcd-6e70-46f9-8d81-9c5237cb7393": "Text2",
"01485828-39ef-4929-9e96-19758375eb9b": "Text3",
}
created_at: "2014-06-25T07:42:19Z",
id: "ea07aaa3-9db6-4868-b6f1-0887ef77f8ba",
product_id: "eb5a7c9c-c20d-4539-b04f-5a3fd8d26c87",
updated_at: "2014-06-25T07:42:19Z"
written_by: "09b3c6f1-cbcb-4544-8cc3-d073d17a8552",
written_on: "2014-06-25"
}


The JS is pretty straight-forward:

var context = {review:review};
html = template(context);


The template is largish but relevant part is here

<textarea class="review-body"> {{body["1cfd0269-1b8f-418f-a7b2-45eb2fa7562b"]}} </textarea>


I am getting a Parse error while trying to access attributes of body in an html template. Any ideas why this is happening?

Uncaught Error: Parse error on line 5:
...iew-edit-context">{{body["1cfd0269-1b8f-418f-a7b2-45eb2fa7562b"]}}</tex
-----------------------^
Expecting 'ID', 'DATA', got 'INVALID'

Answer

From the doc on Handlebars expressions :

To reference a property that is not a valid identifier, you can use segment-literal notation, [ :
{{#each articles.[10].[#comments]}}
{{/each}}

which means you have to use {{body.[1cfd0269-1b8f-418f-a7b2-45eb2fa7562b]}} in your template.

See http://jsfiddle.net/nikoshr/KVg9P/ for a demo.