111:TemplateView講解

TemplateView:

  django.views.generic.base.TemplateView,這個類視圖是專門用來返回模版的。在這個類中,有兩個屬性是常常須要用到的,一個是template_name,這個屬性是用來存儲模版的路徑,TemplateView會自動的渲染這個變量指向的模版。另一個是get_context_data,這個方法是用來返回上下文數據的,也就是在給模版傳的參數的。示例代碼以下:html

from django.views.generic.base import TemplateView

urlpatterns = [
    path('about/', TemplateView.as_view(template_name='about.html')),
  
# 若是就是一個純靜態頁面,就能夠這樣搞 ]

若是有參數能夠以下搞:django

from django.views.generic.base import TemplateView

class aboutPageView(TemplateView):

    template_name = "about.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['username'] = "你大爺的"
        return context

urls.py中的映射代碼以下:app

from django.urls import path
from myapp.views import aboutPageView

urlpatterns = [
    path('', aboutPageView.as_view(), name='about'), ]
相關文章
相關標籤/搜索