djangodjango-templatesdjango-tagging

In a Django template, is it possible to send the whole variable document to a template tag?


If I render a template using this document:

{ "a": 1, "b": 2 }

In Django templates, I can render html using the value of "a" like this:

{{ a }}

But is it possible to send the whole document to a template tag? ie, all this?

{ "a": 1, "b": 2 }

So that my tag can access arbitrary elements?


Solution

  • Just pass your dict as string or you can use json to this for you.

    Example 1

    def index(request):
        my_dict = '{"a":1, "b":2}'
        return render(request, "index.html", {'data':my_dict})
    

    Example 2

    import json
    
    def index(request):
        my_dict = json.dumps({"a":1, "b":2})
        return render(request, "index.html", {'data':my_dict})
    

    and inside your template just do like this

    {{data}} <!--- this will output actual dictionary eg. { "a": 1, "b": 2 } --->