Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

118
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda