Templates with Jinja2 & Static Files
Flask uses Jinja2 as its template engine. Templates allow you to output dynamic HTML, keeping presentation logic separated from Python source code.
1 Rendering a Template
Python — app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/items")
def list_items():
items_list = ["Laptop", "Mouse", "Keyboard"]
return render_template("items.html", items=items_list, title="Inventory")
2 Jinja2 Syntax
HTML — templates/items.html
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
<!-- Link to static files folder -->
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Items list</h1>
<ul>
{% for item in items %}
<li>{{ item|upper }}</li>
{% else %}
<li>No items found.</li>
{% endfor %}
</ul>
</body>
</html>
3 Code Challenge
Challenge: Set up a project containing a
templates/ directory and a static/ directory. Create a base layout template that is inherited by a landing page template, displaying a list of products.