What are Flask Templates?
Flask uses Jinja2 templating engine to render HTML dynamically. Templates allow you to separate presentation from logic, making your code cleaner and more maintainable.
Template Structure
Organize templates:
myapp/
app.py
templates/
base.html
index.html
about.html
static/
css/
js/
Rendering Templates
Render templates from views:
from flask import render_template
@app.route('/')
def home():
return render_template('index.html',
title='Home',
name='Alice')
Template Variables
Display variables using {{ }}:
<!-- template.html -->
<h1>Hello, {{ name }}!</h1>
<p>Welcome to {{ title }}</p>
Template Tags
Use tags for logic with {% %}:
<!-- Conditional -->
{% if user %}
<p>Welcome, {{ user.name }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
<!-- Loop -->
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
Template Inheritance
Create base templates:
<!-- base.html -->
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My App{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
<!-- index.html -->
{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block content %}
<h1>Home Page</h1>
{% endblock %}
Template Filters
Modify variable output:
{{ name|upper }} # Uppercase
{{ name|lower }} # Lowercase
{{ text|truncate(50) }} # Truncate
{{ value|default('N/A') }} # Default value
Including Templates
Include other templates:
{% include "header.html" %}
<h1>Main Content</h1>
{% include "footer.html" %}
URL Generation
Generate URLs dynamically:
<a href="{{ url_for('home') }}">Home</a>
<a href="{{ url_for('user_profile', user_id=user.id) }}">Profile</a>
Static Files
Link to static files:
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<img src="{{ url_for('static', filename='images/logo.png') }}">
Best Practices
- Use template inheritance: Avoid code duplication
- Keep logic minimal: Move complex logic to views
- Use filters: Format data in templates
- Organize templates: Use subdirectories for large apps
Next Steps
Learn about Flask routes or forms for user input.