flask render template
A Flask app needs to put the current date on a html page. The render_template() can help with that.
Firstly create an index.html under /templates directory. The render_template() seems to pick up html files from the /templates directory automatically without extra config.
Use the double braces {{}} to include any data that needs to be on the page.
<html>
{{date}}. Hello.
</html>
Then on the Flask app.
from flask import Flask, render_template
from datetime import date
app = Flask(__name__)
@app.route('/', methods = ['GET'])
def hello():
return render_template('index.html', date = str(date.today()))
When there is a strucutre of data to be consumed, can also use the tojson filter to convert data (with many fields) into json. Then consume data in the subsequent javascript.
<script>
var a = {{ data|tojson }};
</script>
Sometimes it needs if-else and loop logic in the html page.
{% if show_result%}
<table align="left" >
{% for name, description in results %}
<tr>
<td>{{ name }}</td>
<td>{{ description }}</td>
</tr>
{% endfor %}
</table>
{% endif %}
Then render_template('index.html', show_result = True, results = zip(names, descriptions)) will send through the variables.