In today's lab, we will continue to learn how to use the Flask service to make Python-back end apps that serve dynamic HTML data with Jinja.
Use arrays to store data to be displayed
Update content dynamically using the render_template method
Use loops to traverse arrays and populate the Jinja template
Jinja is a modern and designer-friendly templating language for Python
Flask provides support for Jinja2 by default
<ul>
{% for item in seq %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{{ 1 + 1 }}
Returns 2
{{ 1 in [1, 2, 3] }}
Returns true
<ul>
# for item in seq
<li>{{ item }}</li>
# endfor
</ul>
This code is equivalent to the example code for {%...%} above.
{# note: commented-out template
{% for user in users %}
...
{% endfor %}
#}
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def template_test():
return render_template('template.html', coaches="Your Coaches:",
coach_list=["Wolf", "Alex", "Nic"])
if __name__ == '__main__':
app.run(debug=True)
<!--TEMPLATE.HTML-->
<body>
<div class="container">
<p>Meet {{coaches}}</p>
<ul>
{% for n in coach_list %}
<li>{{n}}</li>
{% endfor %}
</ul>
</div>
</body>