As previous speakers have explained, there is a difference in execution time between a jinja template and the JavaScript code.
However, you can pass data to JavaScript inside jinja. The solution is the tojson
filter, which allows you to serialize a python variable to json and then assign it to a variable in JavaScript. It is then possible, for example, to iterate over a resulting array, as in the following example.
from flask import (
Flask,
render_template
)
app = Flask(__name__)
@app.route('/')
def index():
data = [
['one', 'more', 'thing'],
['some', 'thing', 'else']
]
return render_template('index.html', **locals())
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Index</title>
</head>
<body>
<script type="text/javascript">
(function(data) {
data.forEach(row => {
console.log(row[0]);
});
})({{data|tojson}});
</script>
</body>
</html>
If you want to send data from JavaScript to the server for processing in python, send an AJAX request.
from flask import (
Flask,
jsonify,
render_template,
request
)
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html', **locals())
@app.post('/recieve')
def recieve():
data = request.json
print(data)
return jsonify(success=True)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Index</title>
</head>
<body>
<script type="text/javascript">
(function(url) {
const data = [
['one', 'more', 'thing'],
['some', 'thing', 'else']
];
fetch(url, {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(resp => resp.json())
.then(data => console.log(data));
})({{url_for('recieve')|tojson}})
</script>
</body>
</html>