111:TemplateView讲解

TemplateView:

  django.views.generic.base.TemplateView,这个类视图是专门用来返回模版的。在这个类中,有两个属性是经常需要用到的,一个是template_name,这个属性是用来存储模版的路径,TemplateView会自动的渲染这个变量指向的模版。另外一个是get_context_data,这个方法是用来返回上下文数据的,也就是在给模版传的参数的。示例代码如下:

from django.views.generic.base import TemplateView

urlpatterns = [
    path('about/', TemplateView.as_view(template_name='about.html')),
  
# 如果就是一个纯静态页面,就可以这样搞 ]

如果有参数可以如下搞:

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中的映射代码如下:

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

urlpatterns = [
    path('', aboutPageView.as_view(), name='about'), 
]

 

posted @ 2019-02-24 22:11  zheng-weimin  阅读(260)  评论(3编辑  收藏  举报