gokul
gokul

Reputation: 117

Store json object to html element with handlebars

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?

Upvotes: 3

Views: 3071

Answers (1)

Diosney
Diosney

Reputation: 10580

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.

Upvotes: 3

Related Questions