Flask は標準でテンプレートエンジン Jinja2 を採用している。HTML ファイルに Python の変数や制御構文を埋め込むことで、動的なページを生成できる。
テンプレートの基本
テンプレートファイルは templates ディレクトリに配置する。render_template 関数でテンプレートを呼び出し、変数を渡す。
from flask import Flask, render_template app = Flask(__name__) @app.route('/hello/<name>') def hello(name): return render_template('hello.html', name=name)
テンプレート側では {{ }} で変数を展開する。
<!DOCTYPE html> <html> <head> <title>Hello</title> </head> <body> <h1>Hello, {{ name }}!</h1> </body> </html>
制御構文
Jinja2 では {% %} で制御構文を記述する。
{% if user %}
<p>Welcome, {{ user.name }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
if や for は必ず endif、endfor で閉じる必要がある。
テンプレートの継承
共通レイアウトを親テンプレートとして定義し、子テンプレートで継承できる。
<!-- base.html --> <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> {% block content %}{% endblock %} </body> </html>
<!-- hello.html --> {% extends "base.html" %} {% block title %}Hello{% endblock %} {% block content %} <h1>Hello, {{ name }}!</h1> {% endblock %}
{% block %} で定義した領域を子テンプレートで上書きする仕組みである。