Flask Jinja2 Template

Use Jinja2 template for Flask frontend rendering.

Pass Variables

There are two ways passing variables via Jinja2

  1. pass value in render_template
@index_page.route("/")
def index():
    name = "jinja2"
    return render_template("index.html", name = name)
  1. pass a dictionary
@index_page.route("/dict")
def index_dict():
    name = "jinja2"
    context = {"name": name}
    return render_template("index.html", **context)

In html template

<body>
    <h1>Render Template</h1>
    <p>var name = {{name}}</p>
</body>

if

in python file

@index_page.route("/template_dict")
def res_temp_dict():
    data = {
        "name": "Flask Using Dict",
        "company": {
            "name": "Facebook",
            "ticker": "FB",
            "price": 159.6
        },
        "hist": [1, 2, 3, 4, 5, 3, 2, 1]
    }
    return render_template("index.html", **data)

in Jinja2 file

<p>
    {% if company %}
    {{ company.name }}
    Ticker: {{company.ticker}}
    Price: {{company.price}}
    {% endif %}
</p>

for

in Jinja2 file

<p>
    {% for num in hist %}
      <h1>{{num}}</h1>
    {% endfor %}
</p>

Extend Template

In Python file

@index_page.route("/extend_template")
def extend_template():
    return render_template("extend_template.html")


@index_page.route("/extend_template2")
def extend_template2():
    return render_template("extend_template_2.html")


@index_page.route("/extend_template/<username>")
def extend_template_username(username):
    data = {
        "username": username
    }
    return render_template("extend_template_2.html", **data)

In Jinja2 Template

  • common layout file
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>This is common template</title>
</head>
<body>
<h1>Template Header</h1>
{% block content %}
{% endblock %}
<h1>Template Footer</h1>
</body>
</html>
  • Body template file
{% extends "common/layout.html" %}

{% block content %}
<h2>Body starts here</h2>
{% endblock %}

   Reprint policy


《Flask Jinja2 Template》 by Isaac Zhou is licensed under a Creative Commons Attribution 4.0 International License
  TOC