use dict from python in django html template and also in js

36 Views Asked by At

I am having a dict statistics in my view.py and give it as param in my context to my index.html. There I want to use it in my html like {{ statistics.key1 }}. But I also want to use it in js.

When using json.dumps like this in my view.py:

"statistics": json.dumps(statistics, cls=DjangoJSONEncoder),

I can use it like this in my js:

var statistics = JSON.parse('{{ statistics | escapejs }}');

But then I can't use it as a dict anymore in my html. Makes sense, as it is now a JSON-String.

But when I just pass it like a dict, I can use it in my html. but

var statistics = '{{ statistics | escapejs }}' 

gives me a JSON with single quotes so I can't just parse it.

How can I do both? Still use the dict as normal in my HTML and also parse it to use it in js?

0

There are 0 best solutions below