Some sample Flask-Javascript-python examples

1 sample pass object in javascript via json in flask

This example taken from gist.github.com/ischurov

route.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def hello_world():
    user = {'firstname': 'Harry', 'lastname': 'Potter'}
    return render_template("index.html", user=user)

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

With the corresponding html template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello, World</title>
</head>
<body>
<p>Hello, <span id="username"></span></p>
<script>
    var user = JSON.parse('{{ user | tojson | safe}}');
    document.getElementById('username').innerHTML=user.firstname + " " +
            user.lastname;

</script>
</body>
</html>

2 Passing json string to rendered template in Flask

This taken directly from pythonanywhere.com

return render_template('rect.html',string=json)

The html template has this line:

fc = {{string|tojson}}

Which prints weird characters. The correct line should be:

fc = {{string|tojson|safe}}