• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

416
Views
How to update django variable 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?

Let's say code will look like this,

{% if variable_name %}
 <p> Condition is true </p>
{% endif %}
over 3 years ago · Santiago Trujillo
2 answers
Answer question

0

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)

over 3 years ago · Santiago Trujillo Report

0

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>
over 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error