メインコンテンツへスキップ
見出し画像

【第1回】Flaskで画面を出す ― ルーティングとJinja2テンプレート入門

    対象読者: 第0回でFlaskを起動できた人
    この回でやること: 複数ページの作成・テンプレートへの分離・データの受け渡し・入力フォームの土台
    所要時間: 30〜60分

    前回は `return '<h1>Hello!</h1>'` という1行でHTMLを返していました。でも実際のアプリは複数ページがあり、データによって表示内容も変わります。今回はそのための仕組みを作ります。

    動機:なぜテンプレートが必要か

    HTMLをPythonコードの中に直書きしていると、すぐにこうなります。

    # これは破綻する書き方
    @app.route('/')
    def index():
        return '''
        <!DOCTYPE html>
        <html lang="ja">
        <head><meta charset="UTF-8"><title>読書ログ</title></head>
        <body>
        <nav>...長いナビゲーション...</nav>
        <main>
          <h1>今月の読書記録</h1>
          <table>
            <tr><th>タイトル</th><th>著者</th><th>評価</th></tr>
            ... データの数だけ繰り返し ...
          </table>
        </main>
        </body>
        </html>
        '''

    100行を超えたあたりで「どこを直せばいいかわからない」状態になります。

    解決策:HTMLはHTMLファイルに、Pythonはロジックだけを書く。

    Flaskには Jinja2(じんじゃつー) というテンプレートエンジンが組み込まれています。HTMLファイルの中にPythonっぽい記法でデータを差し込める仕組みです。

    フォルダ構成を整える

    まずプロジェクトの構成をこうします。

    my-data-app/
    ├── app.py
    └── templates/         ← ここにHTMLファイルを置く
        ├── base.html      ← 全ページ共通のレイアウト
        ├── index.html     ← トップページ
        └── detail.html    ← 詳細ページ(後で作る)

    `templates` フォルダはFlaskが自動で認識します。名前は必ずこれにします。

    mkdir templates

    STEP 1:最初のテンプレート

    templates/index.html

    <!DOCTYPE html>
    <html lang="ja">
    <head>
      <meta charset="UTF-8">
      <title>読書ログ</title>
    </head>
    <body>
      <h1>📚 読書ログアプリ</h1>
      <p>ようこそ!</p>
    </body>
    </html>

    app.py

    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return render_template('index.html')  # テンプレートを返す
    
    if __name__ == '__main__':
        app.run(debug=True)

    `render_template('index.html')` が「`templates/index.html` を読み込んで返す」命令です。

    `python app.py` で起動してブラウザで確認してみてください。見た目は前回と同じですが、HTMLがPythonコードから分離されました。


    STEP 2:Pythonのデータをテンプレートに渡す

    Jinja2の最大の強みは「Pythonで作ったデータをHTMLに差し込める」点です。

    app.py

    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        # テンプレートに渡すデータを辞書で用意
        books = [
            {'title': 'プロジェクト・ヘイル・メアリー', 'author': 'アンディ・ウィアー', 'rating': 5},
            {'title': 'ハーモニー',                    'author': '伊藤計劃',           'rating': 4},
            {'title': 'マルドゥック・スクランブル',     'author': '冲方丁',             'rating': 5},
        ]
        return render_template('index.html', books=books)
    
    if __name__ == '__main__':
        app.run(debug=True)

    `render_template('index.html', books=books)` のように、キーワード引数でデータを渡すのがポイントです。`books=books` の左側がテンプレート内で使う変数名です。

    templates/index.html

    <!DOCTYPE html>
    <html lang="ja">
    <head>
      <meta charset="UTF-8">
      <title>読書ログ</title>
    </head>
    <body>
      <h1>📚 読書ログ({{ books|length }}冊)</h1>
    
      <table border="1">
        <tr>
          <th>タイトル</th>
          <th>著者</th>
          <th>評価</th>
        </tr>
        {% for book in books %}
        <tr>
          <td>{{ book.title }}</td>
          <td>{{ book.author }}</td>
          <td>{{ '⭐' * book.rating }}</td>
        </tr>
        {% endfor %}
      </table>
    </body>
    </html>

    Jinja2の記法は3種類だけ覚えれば十分:

    記法            用途                        例
    ---------------------------------------------------------------
    {{ 変数 }}      値を表示する                {{ book.title }}
    {% 命令 %}      for/if などの制御構文       {% for book in books %}
    {# コメント #}  HTMLに出力されないコメント  {# TODO: ページネーション #}

    ブラウザをリロードすると、3冊のデータがテーブルで表示されるはずです。


    STEP 3:ページを複数作る(ルーティング応用)

    本のタイトルをクリックしたら詳細ページに飛ぶようにします。

    app.py に追加

    @app.route('/book/<int:book_id>')
    def book_detail(book_id):
        # 実際はDBから取るが、今はダミーデータ
        books = [
            {'id': 0, 'title': 'プロジェクト・ヘイル・メアリー', 'author': 'アンディ・ウィアー',
             'rating': 5, 'memo': 'SF最高傑作のひとつ。一気読みした。'},
            {'id': 1, 'title': 'ハーモニー', 'author': '伊藤計劃',
             'rating': 4, 'memo': 'ディストピアSF。静かな読後感。'},
        ]
        if book_id >= len(books):
            return '本が見つかりません', 404
        book = books[book_id]
        return render_template('detail.html', book=book)

    `int:book_id` がポイントです。URLの一部を変数として受け取り、関数の引数に渡します。`/book/0` にアクセスすると `book_id=0`、`/book/1` だと `book_id=1` になります。

    templates/detail.html

    <!DOCTYPE html>
    <html lang="ja">
    <head>
      <meta charset="UTF-8">
      <title>{{ book.title }}</title>
    </head>
    <body>
      <a href="/">← 一覧に戻る</a>
      <h1>{{ book.title }}</h1>
      <p>著者:{{ book.author }}</p>
      <p>評価:{{ '⭐' * book.rating }}</p>
      <p>メモ:{{ book.memo }}</p>
    </body>
    </html>

    一覧ページにリンクを追加(index.htmlを修正)

    {% for book in books %}
    <tr>
      <td><a href="/book/{{ loop.index0 }}">{{ book.title }}</a></td>
      <td>{{ book.author }}</td>
      <td>{{ '⭐' * book.rating }}</td>
    </tr>
    {% endfor %}

    `loop.index0` はJinja2のfor文で使える変数で、0始まりのインデックスです(`loop.index` だと1始まり)。


    STEP 4:共通レイアウト(テンプレートの継承)

    今は `index.html` と `detail.html` の両方に `<html>` や `<head>` が重複しています。これを共通化するのが テンプレートの継承 です。

    templates/base.html(土台)

    <!DOCTYPE html>
    <html lang="ja">
    <head>
      <meta charset="UTF-8">
      <title>{% block title %}読書ログ{% endblock %}</title>
      <style>
        body { font-family: sans-serif; max-width: 800px; margin: 0 auto; padding: 1rem; }
        nav  { background: #f0f0f0 ; padding: 0.5rem 1rem; margin-bottom: 1rem; }
      </style>
    </head>
    <body>
      <nav>
        <a href="/">📚 読書ログ</a>
      </nav>
    
      <main>
        {% block content %}{% endblock %}
      </main>
    
      <footer style="margin-top: 2rem; color: gray; font-size: 0.8rem;">
        読書ログアプリ
      </footer>
    </body>
    </html>

    `{% block content %}{% endblock %}` が「子テンプレートがここに中身を埋め込む」場所です。

    templates/index.html(書き直し)

    {% extends 'base.html' %}
    
    {% block title %}読書一覧{% endblock %}
    
    {% block content %}
      <h1>今月の読書({{ books|length }}冊)</h1>
    
      <table border="1" cellpadding="6">
        <tr><th>タイトル</th><th>著者</th><th>評価</th></tr>
        {% for book in books %}
        <tr>
          <td><a href="/book/{{ loop.index0 }}">{{ book.title }}</a></td>
          <td>{{ book.author }}</td>
          <td>{{ '⭐' * book.rating }}</td>
        </tr>
        {% endfor %}
      </table>
    {% endblock %}

    `{% extends 'base.html' %}` で継承を宣言し、`{% block content %}` の中に差し込む内容を書くだけです。ナビゲーションやフッターは `base.html` が面倒を見てくれます。


    STEP 5:入力フォームの土台

    新しい本を追加するフォームを作ります。

    app.py に追加

    from flask import Flask, render_template, request, redirect, url_for
    
    # ...省略...
    
    @app.route('/add', methods=['GET', 'POST'])
    def add():
        if request.method == 'POST':
            # フォームから送られたデータを取得
            title  = request.form.get('title', '').strip()
            author = request.form.get('author', '').strip()
            rating = int(request.form.get('rating', 3))
    
            # 次回:ここでDBに保存する
            print(f'追加:{title} / {author} / ⭐{rating}')
    
            return redirect(url_for('index'))  # 追加後に一覧へ戻る
    
        # GETのとき(フォームを表示するだけ)
        return render_template('add.html')

    `methods=['GET', 'POST']` は「このURLはGET(フォームを表示)とPOST(フォームを送信)の両方を受け付ける」という宣言です。

    `request.method` で「今どちらのリクエストか」を判定し、POSTなら保存処理、GETならフォーム表示に分岐します。

    templates/add.html

    {% extends 'base.html' %}
    
    {% block title %}本を追加{% endblock %}
    
    {% block content %}
      <h1>📖 本を追加</h1>
    
      <form method="POST" action="/add">
        <div style="margin-bottom: 1rem;">
          <label>タイトル<br>
            <input type="text" name="title" required style="width: 100%; max-width: 400px;">
          </label>
        </div>
        <div style="margin-bottom: 1rem;">
          <label>著者<br>
            <input type="text" name="author" style="width: 100%; max-width: 400px;">
          </label>
        </div>
        <div style="margin-bottom: 1rem;">
          <label>評価(1〜5)<br>
            <select name="rating">
              <option value="5">⭐⭐⭐⭐⭐(最高)</option>
              <option value="4">⭐⭐⭐⭐</option>
              <option value="3" selected>⭐⭐⭐(普通)</option>
              <option value="2">⭐⭐</option>
              <option value="1">⭐</option>
            </select>
          </label>
        </div>
        <button type="submit">追加する</button>
        <a href="/" style="margin-left: 1rem;">キャンセル</a>
      </form>
    {% endblock %}

    index.html に「追加」リンクを足す

    {% block content %}
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <h1>今月の読書({{ books|length }}冊)</h1>
        <a href="/add">+ 追加</a>
      </div>
      ...
    {% endblock %}

    フォームを送信するとターミナルに `追加:タイトル / 著者 / ⭐3` のようなログが出ます。次回(第2回)でこれをSQLiteに保存します。


    つまずきポイント集

    `TemplateNotFound` エラー

    jinja2.exceptions.TemplateNotFound: index.html

    原因は2パターンあります。

    1. `templates` フォルダの名前が違う(`template` や `Template` など)

    2. `app.py` と `templates/` フォルダが別の場所にある

    `app.py` と `templates/` は同じフォルダに置くのが基本です。

    フォームを送信すると `405 Method Not Allowed`

    # NG:GETしか受け付けない
    @app.route('/add')
    def add():
        ...
    
    # OK:POSTも受け付ける
    @app.route('/add', methods=['GET', 'POST'])
    def add():
        ...

    `url_for` って何?

    return redirect(url_for('index'))

    `url_for('index')` は「`index` という名前の関数が対応するURLを返す」関数です。`'/'` と直書きしてもいいですが、`url_for` を使う習慣をつけると後でURLを変更したときに楽です。

    Jinja2で `|length` 以外によく使うフィルター

    フィルター                      効果                        例
    -----------------------------------------------------------------------------------------
    |length                        リストの長さ                {{ books|length }}
    |default('未設定')             Noneや空文字のデフォルト値  {{ memo|default('メモなし') }}
    |upper                         大文字化                    {{ name|upper }}
    |truncate(30)                  文字数制限                  {{ title|truncate(30) }}

    演習:自分のアプリに当てはめる

    今回作った「読書ログ」を自分の題材に置き換えてみましょう。

    ミッション

    1. `books` リストを自分のデータに変える(ゲームログ・映画記録・家計メモなど)

    2. `index.html` の列名と表示内容を対応させる

    3. `add.html` のフォームのフィールドを自分の項目に変える

    題材が変わってもFlaskとJinja2の使い方は同じです。「データの形(辞書のキー名)」と「HTMLの表示」を合わせるだけです。


    今回の整理

    やったこと                         ポイント
    --------------------------------------------------------------------------------
    render_template()                  HTMLをファイルに分離する
    {{ 変数 }} / {% for %}             テンプレートにデータを差し込む
    {% extends %} + {% block %}        共通レイアウトを継承する
    int:book_id                        URLから変数を受け取る
    methods=['GET', 'POST']            フォームの送受信を処理する
    request.form.get()                 フォームの送信値を取得する

    AIチューターへの質問例

    「Jinja2の `{% if %}` を使って、評価が5のときだけ行の背景色を変えるにはどう書きますか?」

    「`url_for` と直接URLを書く方法の違いとメリットを教えてください」

    「フォームのバリデーション(入力チェック)をFlask側で行うには?」


    次回予告

    第2回:SQLiteに記録を残す

    今回は「追加するとターミナルにprintされるだけ」でした。次回はこのデータをSQLiteデータベースに保存します。

    • `sqlite3`(Pythonの標準ライブラリ)でテーブルを作る

    • 追加・一覧取得・削除のCRUD操作

    • スキーマ設計の考え方(後から変えにくい部分はどこか)

    データが保存・表示されると、一気に「アプリらしく」なります。


    第0回の記事はこちら


     
     
    はじめまして。本業はITインフラエンジニアをしています。 ITテクノロジーの知見から、生成AIによる創作活動、日常の雑談まで、「誰かのヒントになる」をテーマに幅広く投稿していきます。フォローやスキをいただけると励みになります!

    あなたへのおすすめ