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

448
Visualizações
How to iterate over a list of items from Python/Flask using Javascript?

I'm working to create a graph using HTML/JS/Python/Flask and the labels for this line graph should come from a list in Python and then I would use it on a Javascript.

So far I have not been able to successfully iterate over that list in Javascript, I'm getting 4 times the same string on my HTML.

I'm using a code similar to this one:

start.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/', methods = ['GET','POST'])
def home():
    data = ['ABC','DEF','GHI','JKL']
    return render_template('index.html', data = data, len = len(data))

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

index.html

<body>    
   <p id='test'></p>
   <script>
     let text = '';
     for (i=0; i<'{{len}}'; i++){
        text += '{{data | tojson}}[i]' + '<br>'
     }
     console.log(text)
     document.getElementById('test').innerHTML = text;
   </script>
</body>

I'm getting this as an output:

['ABC','DEF','GHI','JKL'][i]
['ABC','DEF','GHI','JKL'][i]
['ABC','DEF','GHI','JKL'][i]
['ABC','DEF','GHI','JKL'][i]

And I'm looking to get this instead:

ABC
DEF
GHI
JKL

The data sent to the Javascript is sent as text and not as a list, if I change this:

text += '{{data | tojson}}[i]' + '<br>'

To this:

text += '{{data | tojson}}'[i] + '<br>'

The output becomes:

[
"
A
B

And the console output is:

[<br>"<br>A<br>B<br>

Do anybody know how to handle this properly so I get the correct results?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

As you might have noticed, I'm a complete beginner when it comes to Javascript, doing some research, I found out I can slice and split in Javascript as well. So I solved my issue by using those two methods.

Giving more detail about what I did, {{data}} is passed over to Javascript as a single string, as '['ABC','DEF','GHI','JKL']', and if you read this string as a console output it shows:

[&#39;ABC&#39;, &#39;DEF&#39;, &#39;GHI&#39;, &#39;JKL&#39;]

To solve this I first sliced the string with:

flask_data = '{{data}}';
temp_array = flask_data.slice(6,-6);

So I get this as a result:

ABC&#39;, &#39;DEF&#39;, &#39;GHI&#39;, &#39;JKL

Then I split the string using the following substring: '', '', as follows:

array = temp_array.split('&#39;, &#39;');

And as a result I got the array I needed:

['ABC','DEF','GHI','JKL']
about 4 years ago · Juan Pablo Isaza Relatório

0

Try this in HTML

<body>    
   <p id='test'></p>
   <script>
     let text = '';
     for (i=0; i<'{{len}}'; i++){
        text += '{{data[i]}}' + '<br>'
     }
     console.log(text)
     document.getElementById('test').innerHTML = text;
   </script>
</body>

or you can also pass a string instead of an array.

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/', methods = ['GET','POST'])
def home():
    data = ['ABC','DEF','GHI','JKL']
    return render_template('index.html', data = "\n".join(data), len = len(data))

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

and then in HTML you can just print this joined string

<body>    
   <p id='test'></p>
   <script>
     document.getElementById('test').innerHTML = {{data}};
   </script>
</body>
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