Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
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 %}
about 4 years ago · Juan Pablo Isaza
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)

about 4 years ago · Juan Pablo Isaza 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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!