Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

302
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda