テンプレートでfor文を使うやり方を記載します。
テンプレートでfor文を使うには、
リストをビュー側から送る必要があります。
ビュー
1 2 3 4 5 6 |
from django.http import HttpResponse from django.shortcuts import render def index(request): message_dict = {'message': [1, 2, 3]} return render(request, 'index.html', message_dict) |
テンプレートで受け取ったリストを使って、
下記のようにfor文を使うことができます。
テンプレート index.html
1 2 3 4 5 6 7 8 9 10 11 |
<!DOCTYPE html> <html> <head> <title>タイトル</title> </head> <body> {% for i in message %} {{i}} {% endfor %} </body> </html> |
index.html 表示結果
ビューから渡したリストをfor文でループさせて、中身を表示した結果が確認できました。