ビューからテンプレートに値を渡す

ビューの変更

今回は関数ベースビューで定義した文字列をテンプレートに渡します。「test_app/views.py」を以下のように記述します。

# test_app/views.py
from django.shortcuts import render
 
def top_page(request):
    context  = {
        'message': 'Test from view'
    }
    return render(request, 'test_app/top_page.html', context)

top_page 関数内で context という辞書を作成しています。 context という変数名は変更可能で、辞書型のデータをテンプレートに渡すことができます。

テンプレートの変更

「test_app/top_page.html」を以下のように変更します。

<!-- test_app/templates/test_app/top_page.html -->
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <title>トップページ</title>
    </head>
    <body>
        <h1>{{ message }}</h1> <!-- ← ここでビューからの文字を表示 -->
    </body>
</html>

開発サーバーを起動した状態で「http://127.0.0.1:8000/」にアクセスするとviewで定義した「Test from view」が表示されました。

ブレークポイントを設定してみるとmessageという変数に「Test from view」が渡されていることが確認できます。

コメント

タイトルとURLをコピーしました