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

303
Vistas
How to pass variable from Flask app to Javascript file

I know this has been asked probably asked before but for some reason it is not working for me. Code:

app.py

from flask import Flask, request
from flask.templating import render_template

app = Flask(__name__)
app.secret_key = 'mysecret'
app.config["TEMPLATES_AUTO_RELOAD"] = True

@app.route("/")
def index():
    items = ["backpack", "handbag", "laptop"]
    return render_template("index.html", items=items)


if __name__ == "__main__":
    app.secret_key = 'mysecret'
    app.run(debug = True)

index.html

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" {{ url_for('static', filename='app.js')}}></script>
    <script type="text/javascript">
        var data = '{{ items }}'
        myFunc(data)
    </script>
</head>
<body>
    <div id="dvTable"></div>
</body>
</html>

app.js

function myFunc(data) {
    var table = document.createElement("table");
    row = table.insertRow(-1);
    var cell = row.insertCell(-1);
    cell.innerHTML = 'Item';
    for (var i = 0; i < data.length; i++)
    {
        var cell = row.insertCell(-1);
        cell.innerHTML = data[i];
    }
    var dvTable = document.getElementById("dvTable");
        dvTable.innerHTML = "";
        dvTable.appendChild(table);
}

This is not returning anything on the screen. There are no exceptions. Please tell me what's the issue here?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can convert the variable within jinja2 into a json object using the built-in filter tojson.

var data = {{ items | tojson }}


When executing a javascript function which is to change DOM elements, it is important to ensure that these are already loaded. One possibility is the listener used in my example. Another possibility is to put the script tags at the end of the file.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script type="text/javascript" src="{{ url_for('static', filename='app.js') }}"></script>
    <script type="text/javascript">
      (function(items) {
        document.addEventListener('DOMContentLoaded', function() {
          myFunc(items);
        });
      })({{ items | tojson }});
    </script>
  </head>
  <body>
    <div id="dvTable"></div>
  </body>
</html>
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