[Answered ]-Django pass var from view to two template in the same time

2đź‘Ť

âś…

assuming you want to keep your javascript files js only, one way to achieve this is to have your js initialize accept some config data. in your html template (which is rendered by django and thus has access to your context vars you pass data in

javascript.js

...
function initialize(options) {
...

template.html

<input type="submit" value="Submit" onclick="initialize({
    myvar: {{ value_from_django }},
    other_stuff: 10
})">
👤second

0đź‘Ť

You don’t need to “pass” the variable to the library.

Just set it in a script tag like so:

{% block library %}
<script type="text/javascript">
    var foo = "{{ variable }}";
</script>
<script type="text/javascript" src="/static/javascript.js"></script>
{% endblock %}

You can then reference it within your JS as either VARIABLE or window.foo.

👤Jack Shedd

Leave a comment