テンプレートの使用

ルーティングの設定

以下を参照し、ルーティングの設定をあらかじめ行ってください。

Viewの作成

test_app/views.py を以下のように変更します。

from django.shortcuts import render
  
def top_page(request):
    return render(request, 'test_app/top_page.html')

render とは?

render は テンプレート(HTMLファイル)を使ってページを作って返すときに使います。

テンプレートの作成

「myapp/test_app/」配下に「templates/test_app」を作成します。

mkdir -p ~/work/test_project/test_app/templates/test_app

テンプレート「top_page.html」を作成します。

touch ~/work/test_project/test_app/templates/test_app/top_page.html

現在のディレクトリ構造はこのような感じになっていると思います。


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>ようこそ、トップページへ!</h1>
        <p>Djangoのrenderでこのテンプレートが表示されています。</p>
    </body>
</html>

ブラウザから「http://127.0.0.1:8000/」にアクセスした時、以下のように表示されればOKです。

コメント

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