系统环境:Win7 bit64 Anaconda2
Django版本:1.8.16 前面都是用简单的 django.http.HttPResponse 来把内容显示到网页上,本节将讲解如何使用渲染模板(*.html)的方法来显示内容。
在myapp/views.py中写一个首页视图
from django.shortcuts import renderdef home(request): return render(request, 'home.html')在myapp目录下建立templates文件夹,里面新建home.html
<!DOCTYPE html><html><head> <title>NetBook</title></head><body>welcome to netbook!</body></html>更改myproject/urls.py
from django.conf.urls import include, urlfrom django.contrib import adminfrom myapp import views as myapp_viewsurlpatterns = [ url(r'^$', myapp_views.home, name='home'), url(r'^admin/', include(admin.site.urls)),]向模板传递变量,修改views.py
# -*- coding: utf-8 -*-from django.shortcuts import renderdef home(request): string = u"我在学习Django,用它来建网站" return render(request, 'home.html', {'string': string})字符串string被传给home.html,在hime.html调用string
{{string}}
传递列表,view.py
def home(request): TutorialList = ["HTML", "CSS", "jQuery", "Python", "Django"] return render(request, 'home.html', {'TutorialList': TutorialList})home.html
教程列表:{% for i in TutorialList %}{{ i }}{% endfor %}使用for循环输出列表内容。
参考:http://www.ziqiangxuetang.com/django/django-template.html
新闻热点
疑难解答