テンプレートの利用
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
これはサンプルページです。