CodeToLive

Flask Templates with Jinja2

Flask uses the Jinja2 template engine to render dynamic HTML content. Templates help separate presentation from application logic.

Basic Template Rendering


from flask import render_template

@app.route('/')
def index():
    return render_template('index.html', title='Home')
            

Template Inheritance

base.html:


<!DOCTYPE html>
<html>
<head>
    {% block title %}{% endblock %}
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>
            

index.html:


{% extends "base.html" %}

{% block title %}{{ title }}{% endblock %}

{% block content %}
    <h1>Welcome to {{ title }}</h1>
{% endblock %}
            

Template Variables


<p>Hello, {{ user.username }}!</p>
<p>Your score is {{ score|round(2) }}</p>
            

Control Structures


{% if user %}
    <p>Welcome back, {{ user.username }}!</p>
{% else %}
    <p>Please log in.</p>
{% endif %}

{% for item in items %}
    <li>{{ item.name }}</li>
{% endfor %}
            

Filters


{{ name|capitalize }}
{{ message|truncate(50) }}
{{ list|join(', ') }}
            

Macros


{% macro render_comment(comment) %}
    <div class="comment">
        <p>{{ comment.text }}</p>
        <small>By {{ comment.author }}</small>
    </div>
{% endmacro %}

{{ render_comment(comment) }}
            

Template Context


@app.context_processor
def inject_user():
    return dict(user=g.user)
            

Static Files


<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<script src="{{ url_for('static', filename='script.js') }}"></script>
<img src="{{ url_for('static', filename='logo.png') }}">
            
Next: Forms & Validation