Django.fun

How to update django vairable inside javascript

Like we can access a variable in the JS part like "{{vaiable_name}}". How can we update the value of variable_name inside the javascript?

Answers: 2

Answered by nigel222, Dec. 3, 2021, 5 p.m.

One way is to inject a small Javascript through the Django template engine, with {{variable}} substitution.

My own base.html contains

<script type="text/javascript"> $(document).ready(  function() {
    {% block onready_js %}{% endblock onready_js %}   
  }); 
</script>

and then in any template extending base.html where I want to pass variable values, I can simply code

 {% block onready_js %}
      /* some JS with Django substitutions */
      var foo = "{{foo}}";
      ...
 {% endblock %}

The one thing you have to remember is that your JS must not contain consecutive open- or close-braces without a space between them!

(If the block is not defined, then the base.html defines a null function to be executed when the document is ready)

Answered by user14665310, Dec. 3, 2021, 9:46 p.m.

you can add a span tag with an id and then target the id within javascript

<span id='django_variable_id'>{{variable_name}}</span>

<script>
function update_django_variable(new_var){
    /* get the span element */
    var span = document.getElementById('django_variable_id');
    /* set new var here */
    span.innerText = new_var;
}
</script>

or will also work as long as there are no other variables with this name

<span id='var_{{variable_name}}'>{{variable_name}}</span>

<script>
function update_django_variable(new_var){
    /* get the span element */
    var span = document.getElementById('var_{{variable_name}}');
    /* set new var here */
    span.innerText = new_var;
}
</script>