Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 203
gokul Avatar asked Dec 30 '25 14:12

gokul


1 Answers

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.

like image 159
Diosney Avatar answered Jan 02 '26 04:01

Diosney