开发者

global variable from django to javascript

开发者 https://www.devze.com 2022-12-19 01:03 出处:网络
I would like some variables from my settings.py to be available in every javascript running across my project.

I would like some variables from my settings.py to be available in every javascript running across my project.

What is the most elegant way of achieving this?

Right now I can think of two:

  • w开发者_如何学运维rite a context processor and declare those globals in a base template. All templates must extend the base template.

  • declare those globals in a dynamically generated .js file (by some view) and load this file using <script> tag in a base template. All templates must extend the base template.

Can I do it without a base template?


I would use option 1. You should use a base template in any case, and a context processor is probably the best way of getting the variables into it.


I'm not familiar with django, so this might be completely incorrect.

Can you write out the variables to hidden HTML fields on the page. This will allow you to access them from JavaScript, or utilise them in form posts should you require that.


I have the same problem, and I'm using an ugly solution with a “refactor later” note.
I put a js_top block at the top of my base template, and then any template who needs additional includes or js variables set can use that block.
So I have stuff such as this:

{% 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 have need of a more robust and less “one-off” system, I'd go with the generated js.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号