Django: store a json string as data attribute in Django template

Viewed 201

In Django i am passing a json string to template and want to store it as a data attribute in an html tag and later use that json string in Jquery

Like

def sampleView(request)
    data = {"param1": 1, "param2": "testing"}
    json_string = json.dumps(data,indent=4,default=str)
    return render(request, 'my_home.html', dict(data=json_string))

Now i want to store it as a data attribute in html

my_home.html

....

<div id="test" data-sample={{ json_string }}>....

....

and in jquery i want to convert back to json.

How can i do it

1 Answers

wrap it in single quotes

<div id="test" data-sample='{{ json_string }}'>

then you can convert it to a JSON object in JQuery (but I think it runs JSON.Parse(x)) automatically

You can also do

'{{ some_python_dict | jsonify }}'

instead of converting it to json in the view

Related