Search code examples
pythondjangodjango-viewsdjango-templates

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


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?


Solution

  • How about creating a custom template filter in Django to transform Python objects into JSON?

    Example steps:

    1. In your Django app, create a templatetags directory if it does not already exist.

    2. In this directory, create a file called json_filters.py (or any other name you prefer). It will look something like this:

    import json
    from django import template
    from django.core.serializers.json import DjangoJSONEncoder
    
    register = template.Library()
    
    @register.filter(name='to_json')
    def to_json(value):
        return json.dumps(value, cls=DjangoJSONEncoder)
    
    1. load your filter in the template file before using it:
    {% load json_filters %}
    
    <script>
    var statistics = JSON.parse('{{ statistics | to_json | escapejs }}');
    </script>
    

    The to_json filter transforms your Python dictionary into a JSON string. This is then processed by the escapejs filter to ensure any characters that have special meaning in JavaScript are safely escaped.