0

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?

Mike
  • 609
  • 12
  • 36
  • The proper terminology for what you call "document" is "context" in Django. And can you clarify? Are you writing a custom template tag and want to access the entire context there? Or you are using some builtin template tag? – Abdul Aziz Barkat Jul 22 '22 at 13:45
  • Hi Abdul, yes the entire document is placed there – Mike Jul 22 '22 at 14:28

2 Answers2

1

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 } --->
Ankit Tiwari
  • 4,438
  • 4
  • 14
  • 41
0

In django framework we send data from view.py to template using context dictionary. The general format for this is:

  1. using function based views.

    def index(request):

    return render(request, 'index.html',{'injectme':'this is context',
    'inject_me':'this is next context'})
    

now in template you can access this as:

{{injectme}}    
{{inject_me}}
  1. using class based views

    class abc(TemplateView):

    def get_context_data(self,**kwargs):
        context=super().get_context_data(**kwargs)
        context['inject_me']='basic injection'
        context['injectme']='second injection'
        return context
    

now in the template:

{{inject_me}}
{{injectme}}

hope your confusion cleared out.

  • Thanks Ran, this was not my question though. I wanted to be able to send the whole document to a tag, so I was able to add an extra tag in the context by adding an additional "context" node with a deepcopy of the document for convenience. – Mike Jul 22 '22 at 16:57