passing Django context data to an external .js file

hello friend which way is the best way to pass a Django’s views.py context data into an external javascript file, so as to run the js function.
for example i pass the value ‘product_price’ into a context then display it in a html page using the jinja tag.
now, what way is the best way to pass it to an external js file which has been included in the base .html
i read up somethings where json_script was suggested and another where the jinja tag was suggested. so i decided to ask the pro. which way should i do it

1 Like

Are you talking about needing to do this in the initial rendering? Or are you talking about doing this as the result of an AJAX call?

If the first, can you be more specific about what it is you’re trying to achieve? Are you actually using Jinja in Django? Or are you using the Django template language?

I know the json_script filter works extremely well, I use it myself.

But this is one of those “there’s no real ‘right’ or ‘wrong’ answer here, it’s whatever you’re comfortable with” type of situations.

Go with whatever fits your mindset and looks the most readable to you.

Ken

On json_script, my blog post covers more information: https://adamj.eu/tech/2020/02/18/safely-including-data-for-javascript-in-a-django-template/

There are some “wrong” ways that add security vulnerabilities :wink:

1 Like

hi thanks for your time ken

great article. thank you, i hope it works or me