3

how to store the json complete object in html element as a data attribute

var a = {name : "sample",age : "34"}
$.find('#someDiv").data("adata",a);

can we achive the same thing with handlebars while creating the template

<div id="someDiv" data-adata="{{a}}"></div>

is that possible?

gokul
  • 117
  • 1
  • 14
  • right now i have stringyfied the json and stored it according as specified in here http://stackoverflow.com/questions/10232574/handlebars-js-parse-object-instead-of-object-object ,is there any direct approch with handlebars – gokul Mar 18 '14 at 10:01
  • oops. I don't see your comment while answering :) – Diosney Mar 19 '14 at 14:41
  • If you want to store a reference to the actual object instead of the JSON string, try this similar question: https://stackoverflow.com/a/57313280/1075062 – Etherman Aug 01 '19 at 16:25

1 Answers1

3

You can't embed JSON perse in the HTML, since HTML is pure string and JSON not.

But you do can stringify it and store it there with a custom method like the following:

/*
 * Simple helper to stringify an object.
 * Usage: {{ JSON2string object }}
 */
Handlebars.registerHelper('JSON2string', function (object:Object) {
    return JSON.stringify(object);
});

Then, in the templates, you can use it like:

<div id="someDiv" data-adata="{{JSON2string a}}"></div>

Which effectively store a JSON string in the data attribute.

Diosney
  • 10,520
  • 15
  • 66
  • 111