この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:3
ページ更新者:ぼうず
更新日時:2026-05-15 05:24:41

タイトル: クラスベースビューでテンプレートに値を渡す方法
SEOタイトル: クラスベースビューでテンプレートに値を渡す方法

1. ビューでcontextを定義する

まず、ビューでテンプレートに渡す変数を定義します。クラスベースビューでは、get_context_dataメソッドをオーバーライドして、contextを定義します。

from django.views.generic import TemplateView

class SampleView(TemplateView):
    template_name = 'sample.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = 'Sample Title'
        context['description'] = 'This is a sample description.'
        return context

上記の例では、titleとdescriptionという変数を定義しています。

 

2. テンプレートでcontextを参照する

次に、テンプレートで定義したcontextを参照します。テンプレートでは、{{ }}で変数を囲んで参照します。




    {{ title }}


   

{{ description }}



上記の例では、titleとdescriptionという変数を参照して、タイトルと本文を表示しています。

 

3. ビューでテンプレートに渡す値を増やす

ビューでテンプレートに渡す値を増やす場合は、get_context_dataメソッドで定義します。

from django.views.generic import TemplateView

class SampleView(TemplateView):
    template_name = 'sample.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = 'Sample Title'
        context['description'] = 'This is a sample description.'
        context['items'] = ['item1', 'item2', 'item3']
        return context

 

上記の例では、itemsという変数を定義して、リストを渡しています。

 

4. テンプレートで渡されたリストを表示する

テンプレートで渡されたリストを表示する場合は、forループを使用して順次表示します。




    {{ title }}


   

{{ description }}


   

            {% for item in items %}
           
  • {{ item }}

  •         {% endfor %}
       


以上がクラスベースビューからテンプレートに値を渡す方法になります。テンプレートの中身を適宜編集して、データを表示させることができます。