👋
【Django】Pythonで作るRest API【8templateの設定】
【8templateの設定】
YouTube: https://youtu.be/8CKCkcJFb9c
今回は「template」を作成して、
HTMLファイルを表示します。
テンプレートを使用するのはこの動画だけですので、
自分の画面で表示してみたいという方だけ実践してください。
まずは「myapp」-> 「posts」の中に「templates」のフォルダを作成します。
そして「templates」の中に「posts」のフォルダを作成して、
「posts」に「index.html」を作成します。
myapp/posts/templates/posts/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Posts Hello</h1>
</body>
</html>
こちらが作成できましたら、
「views.py」でテンプレートを使用できるように
「render」の設定を追加します。
myapp/posts/views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def helloWorld(request):
# return HttpResponse('Hello World')
hello = 'hello'
return render(request, 'posts/index.html', {})
「render」の第3引数にオブジェクトでデータを渡すと、
テンプレートのHTMLで渡されたデータを読み込むことができます。
テンプレートを使用すると、
フロントエンドとバックエンド双方の実装が可能となります。
Discussion