Flask テンプレートレンダリング API

Flask は Jinja2 エンジンを使用してテンプレートをレンダリングし、Python データを HTML ページに埋め込みます。

テンプレートファイルはデフォルトでプロジェクトルートディレクトリのtemplates/フォルダー内に配置されます。


render_template

最も一般的に使用されるテンプレートレンダリング関数で、ファイルからテンプレートを読み込んでレンダリングします。

パラメータ 型 説明
template_name_or_list str / list テンプレートファイル名(templates フォルダーからの相対パス)、またはテンプレート名のリスト(最初に存在するものを返す)
**context キーワード引数 テンプレートに渡す変数。例: title="Hello", user=user_obj

すべてのレンダリング関数

関数 説明
render_template(template_name_or_list, **context) ファイルからテンプレートをレンダリングし、HTML 文字列を返す
render_template_string(source, **context) 文字列からテンプレートをレンダリング。埋め込み型テンプレートに適しています
stream_template(template_name_or_list, **context) テンプレートをストリーミングレンダリングし、ジェネレーターを返します。大規模なページに適しています
stream_template_string(source, **context) 文字列テンプレートをストリーミングレンダリング
get_template_attribute(template_name, attribute) テンプレート内のマクロまたは変数を取得します。Python から Jinja2 マクロを呼び出せます

テンプレート内の組み込みオブジェクト

以下のオブジェクトはテンプレート内で明示的に渡さなくても使用できます:

オブジェクト 説明
request 現在のリクエストオブジェクト
session 現在の Session オブジェクト
g リクエストレベルのグローバルオブジェクト
config アプリケーション設定ディクショナリ
url_for URL生成関数
get_flashed_messages Flask メッセージ取得関数

コード例

例

from flask import Flask, render_template, render_template_string

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html",
                          title="サンプル ホーム",
                          posts=[{"id": 1, "title": "記事A"},
                                 {"id": 2, "title": "記事B"}])

@app.route("/inline")
def inline_template():
    # 文字列からレンダリング(テンプレート内容をコードに直接記述)
    return render_template_string("""
        <h1>Hello, {{ name }}!</h1>
        <p>Welcome to サンプル.</p>
    """
, name="World")

@app.route("/stream")
def stream_large_page():
    # 大きなページをストリーミングレンダリングし、生成しながら送信
    return stream_template("large_report.html",
                          items=get_10k_items())
その他の拡張