巳年じゃないけど Python やろうぜ(その 5)
前回からの続きです。
Hello ページを作る(続き)
HttpResponse
に HTML を渡すための方法として、テンプレートを用いることにします。
まず django_test\hello
の下に templates
というフォルダを作り、さらにその中に hello
というフォルダを作ります(このようにするわけは後で説明します。)
django_test\hello\templates\hello\hello.html
を以下の内容で作成します。
<!doctype html> <html> <head> <title>Hello Page</title> </head> <body> <p>Hello, Django!</p> </body> </html>
django_test\hello\views.py
を以下のように修正します。
from django.template import loader # 追加 from django.http import HttpResponse def index(request): template = loader.get_template('hello/hello.html') html = template.render() return HttpResponse(html)
サーバを起動して確認してみましょう。
テンプレートの置き場所として、templates
フォルダの中にもう一度 hello
フォルダを作りましたが、これには理由があります。Django では、仮に
django_test\foo\templates\index.html
django_test\bar\templates\index.html
と、異なるアプリで同名のテンプレートがあったとき、常に 先に検出した テンプレートを読み込んでしまいます。そのため、意図しないテンプレートを読み込んでしまわないように「名前空間」を付けて
django_test\foo\templates\foo\index.html
django_test\bar\templates\bar\index.html
のように管理するわけです。
ビューで使える便利なショートカット
テンプレートを読み込んで、それをレンダリングして HttpResponse
に渡す、といった処理は頻繁に行います。そのため django.shortcuts
に render
という関数が用意されています。
from django.shortcuts import render def index(request): return render(request, 'hello/hello.html')
この 1 行目は、最初に hello
アプリを作った直後の views.py
のものと同じです。それだけよく使う、ということで、最初から用意してくれているんですね。ちなみに render_to_response
というのもありますが、公式ドキュメントによると非推奨、かつ将来的に廃止予定になるようです。
テンプレートに変数を埋め込む
実際にはどっか(データベースとか)から取得してきたデータをテンプレートに渡して値を埋め込むような処理をすることが多いでしょう。公式ドキュメントを見ると、render
の第三引数に辞書を渡すことでそれができることが分かります。
from django.shortcuts import render def index(request): my_name = 'Django' return render(request, 'hello/hello.html', {'my_name': my_name})
<!doctype html>
<html>
<head>
<title>Hello Page</title>
</head>
<body>
<p>Hello, {{ my_name }}!</p>
</body>
</html>
テンプレートの方に独特の記法が出てきました。これが Django のテンプレートならではの記法です。今後いろいろなところで出てきます。ちなみに拡張子は html
のままで大丈夫です。