简体   繁体   中英

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?

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>

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM