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?

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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.