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?
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>