Global variable from django to javascript

I would like some of the variables from my settings.py to be available in every javascript working in my project.

What is the most elegant way to achieve this?

Now I can think of two:

  • write a context processor and declare these global variables in the base template. All templates must extend the base template.

  • declare these global variables in a dynamically generated .js file (according to some sources) and load this file using the <script> in the base template. All templates must extend the base template.

Can I do this without a basic template?

+4
source share
3 answers

I would use option 1. In any case, you should use a basic template, and probably the best way to get the variables in it would be, for example, a context processor.

+6
source

I am not familiar with django, so this may be completely wrong.

Can you write variables to hidden HTML fields on the page. This will allow you to access them from JavaScript or use them in form messages if you require it.

+1
source

I have the same problem and am using an ugly solution with the notation "refactor later".
I put the js_top block at the top of the base template, and then any template that needs extra includes or a set of js variables can use this block.
Therefore, I have things like:

 {% block js_top %} <script src="/jquery.useless-plugin.js" type="textjavascript"></script> <script type="textjavascript"> var myVar = {{my_variable.propriety}}; </script> {% endblock %} 

Of course, if you need a more reliable and less "one-time" system, I would go with the created js.

0
source

Source: https://habr.com/ru/post/1300395/


All Articles