📝
Django開発入門4:テンプレートにデータを渡す
データを含めてページを作るようにviews.pyを書き換える
renderの第三引数にデータを入れるとテンプレートに渡すことができます。
bbs/views.py
def index(request):
context = {
'message': 'bbsテストです!',
'players': ねこちゃん
}
return render(request, 'bbs/index.html', context)
テンプレートを書き換える
{{}}の中にpythonコードを書けます。
ただし、forやifは{% endfor %}{% endif %}が必要になります。
bbs/templates/bbs/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>bbs test!</title>
<style>body {padding: 10px;}</style>
</head>
<body>
<h1>bbs test</h1>
<p>{{ message }}</p>
{% for player in players %}
<p>{{ player }}はモンスターと戦った</p>
{% endfor %}
</body>
</html>
Discussion