还是在视图层中Templates中进行
-
项目包/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^student/', include('student.urls')),
]
-
应用包/urls.py
#coding=utf-8
from django.conf.urls import url
import views
urlpatterns=[
url(r'^query1/$',views.query_view1)
]
创建视图
-
方式1:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
from django.template import Template,Context
# Create your views here.
def query_view1(request):
t = Template('hello:{{name}}')
c = Context({'name':'zhangsan'})
renderStr = t.render(c)
return HttpResponse(renderStr)
-
方式2:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
from django.template import Template,Context
# Create your views here.
def query_view1(request):
with open('templates/index.html','rb') as fr:
content = fr.read()
t = Template(content)
c = Context({'name':'lisi'})
renderStr = t.render(c)
return HttpResponse(renderStr)
创建模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
hello:{{ name }}
</body>
</html>
-
方式3:
创建视图
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
from django.template import Template,Context
from django.shortcuts import loader
# Create your views here.
def query_view1(request):
t = loader.get_template('index.html')
renderStr = t.render({'name':'wangwu'})
return HttpResponse(renderStr)
-
方式4:
配置视图
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def query_view1(request):
return render(request,'index.html',{'name':'zhaoliu'})
settings.py
在settings文件中配置很多的东西,引擎,路径啊之类的
今天来说Templates变量,都知道开始的html文件都放在里边吧
然后今天我们来重新建立一个目录也叫templates 下面也存有html
依然可以访问的
TEMPLATES = [
{
#渲染引擎
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')] # html模板存放的位置
,
'APP_DIRS': True,
# 当项目下的templates目录中找不到页面会继续到应用包下的templates目录中查找
'OPTIONS': {
'context_processors': [ # 全局上下文
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]