テンプレートの利用
INSTALLED_APPS
へのアプリの登録
Django のテンプレートシステムから自作のアプリを検索できるように、django_app/settings.py
にアプリを登録する必要がある。
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello', ]
テンプレートの置き場所
テンプレートはアプリケーションごとにプロジェクト名/アプリ名/templates/アプリ名
というDIRを作って置く。
今回の helloアプリならdjango_app/hello/templates/hello
。
テンプレートの表示
index.html
テンプレート
hello/templates/hello/index.html
を用意する。
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>hello</title> </head> <body> <h1>hello/index</h1> <p>This is sample page.</p> </body> </html>
urlpatterns
の修正
hello/urls.py
を最初やったような次の形にする。
urlpatterns = [ path('', views.index, name='index'), ]
index関数
の修正
hello/views.py
も次のように修正。
from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, 'hello/index.html')
テンプレートへの変数の埋め込みとかはまだやっていないが、これでとりあえずテンプレートのHTMLが表示される。
hello/index
This is sample page.
render関数
hello/views.py
のindex関数
内で呼び出したrender
は、テンプレートをレンダリングする関数。Djangoに用意されたショートカット関数と呼ばれるもの。本来Loader
というテンプレート読み込みクラスを使ってテンプレートを読み込み、読み込んだオブジェクトからrender
メソッドを呼び出すところを、簡単に使えるようにしたもの。
render(<HttpRequest>, テンプレート, パラメータ)
第一引数 : HttpRequestインスタンス
第二引数 : テンプレート・ファイルへのパス
第三引数 : テンプレートに渡すパラメータ
テンプレートに値を渡す
本来のテンプレートの目的である、値を渡して表示するということをやってみる。
index.html
テンプレートの修正
テンプレートには{{変数名}}
という形でパラメータを埋め込むことができる。
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{title}}</title> </head> <body> <h1>{{title}}</h1> <p>{{msg}}</p> </body> </html>
index関数
からパラメータを渡す
hello/views.py
のindex関数
内からrender
にパラメータを渡す。
def index(request): params = { 'title': 'Hello/Index', 'msg': 'これはサンプルページです。', # 'goto': 'next', } return render(request, 'hello/index.html', params)
これでテンプレート内の{{パラメータ}}
が値に置き換えられて次のように表示される。
Hello/Index
これはサンプルページです。