Home > Enterprise >  Pass a Python list to JavaScript
Pass a Python list to JavaScript

Time:02-28

I'm having some issues passing a Python list to JavaScript as an array. My code is below, and outputs a blank screen, with error: 'Uncaught ReferenceError: array is not defined'.

main.py

from flask import Flask, render_template
import json

app = Flask(__name__)

@app.route('/')
def my_view():
    array = [1, 2, 3, 4, 5]
    jsarray = json.dumps(array)
    return render_template('index.html', array=jsarray)

app.run()

index.html

<script>
    var data = JSON.parse(array)
    document.write(data)
</script>

CodePudding user response:

You can use the Jinja2 filter tojson. A conversion of the data to JSON within the route is not necessary. You can simply pass the list to the template.

@app.route('/')
def my_view():
    array = [1, 2, 3, 4, 5]
    return render_template('index.html', array=array)
<script>
   const data = {{ array | tojson }};
   console.log(data);
</script>

CodePudding user response:

change your index.html to

index.html

<script>
    var data = JSON.parse({{ array }})
    document.write(data)
</script>
  • Related