Michael Hays
Michael Hays

Reputation: 3223

Pass JSON data in Django context

Normally, if I want to return JSON data from a Django view, I can use a JsonResponse like so:

from django.http import JsonResponse

def my_view(request):
    return JsonResponse({'my_key': 'my_value'})

That data is sent to the frontend as a JavaScript object that I can immediately use.

I'd like that same ease of use added to the context of a view, like so:

class WebsiteView(TemplateView):
    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['my_var'] = {'my_key': 'my_value'}
        return context

However, rendering the template with {{ my_var }} gives:

{"my_key": "my_value"}

Ultimately, what I want is for {{ my_var }} to return the plain string rather than the HTML encoded version:

{"my_key": "my_value"}

This way, I can easily load it into a JavaScript object with JSON.parse('{{ my_var }}').

I know that one way to achieve this is by manually unescaping the HTML entities, but I was wondering if there was a better way to do this.

Upvotes: 0

Views: 4123

Answers (1)

aaronfay
aaronfay

Reputation: 1692

As mentioned in the Django template documentation you should be able to do use the |safe filter in your template:

{{ my_var|safe }}

This should instruct the Django template engine to render the data verbatim.

Upvotes: 5

Related Questions