NelsonLabs
Flask/Jinja2 Templates

Jinja2 Templates

Flask uses Jinja2 for templating — a powerful template engine that supports inheritance, macros, filters, and all the control flow you'd expect.

Rendering templates
python
from flask import Flask, render_template

app = Flask(__name__)
# Flask looks for templates in a 'templates/' folder by default

@app.route("/")
def index():
    courses = Course.query.all()
    return render_template("index.html", courses=courses, title="Courses")
templates/base.html
html
<!DOCTYPE html>
<html lang="en">
<head>
  <title>{% block title %}NelsonLabs{% endblock %}</title>
  <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}" />
</head>
<body>
  <nav>
    <a href="{{ url_for('index') }}">Home</a>
    <a href="{{ url_for('courses') }}">Courses</a>
  </nav>

  {% with messages = get_flashed_messages(with_categories=true) %}
    {% for category, message in messages %}
      <div class="alert alert-{{ category }}">{{ message }}</div>
    {% endfor %}
  {% endwith %}

  <main>
    {% block content %}{% endblock %}
  </main>
</body>
</html>
templates/index.html — child template
html
{% extends "base.html" %}

{% block title %}Courses — NelsonLabs{% endblock %}

{% block content %}
<h1>{{ title }}</h1>

{% for course in courses %}
  <div class="course-card">
    <h2>{{ course.title }}</h2>
    <p>{{ course.description }}</p>
    <a href="{{ url_for('course_detail', slug=course.slug) }}">Learn more</a>
  </div>
{% else %}
  <p>No courses yet.</p>
{% endfor %}
{% endblock %}