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

Time:07-23

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?

CodePudding user response:

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 } --->

CodePudding user response:

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.

  • Related