工作中Django总结之二(模板)

模板应用实例(MVC)

在项目project根目录下创建templates目录并建hello.html文件,目录结构为:

project
|--project(文件夹)
|--templates(文件夹)
|--manage.py(文件)

project/templates/hello.html文件代码如下:

<h1>{{ hello }}</h1>
这里的hello是占位符,需与view.py文件中的配置一致。

project/project/settings.py文件中的代码如下:

修改位置:
...TEMPLATES = [
    ......
    'DIRS':[BASE_DIR+"/templates",],
    ......
]

project/project/view.py 文件修改如下:

# _*_ coding:utf-8 _*_

#from django.http import HttpResponse
from django.shortcuts import render
def hello(request):
    context          = {}
    context['hello'] = 'Hello World!'
    return render(request, 'hello.html', context)

 使用render来代替之前使用的HttpResponse.render还使用了一个字典context作为参数。
 context字典中元素的键值'hello'对应了模板中的变量"{{hello}}"    

project/project/urls.py中的代码修改如下:

from django.conf.urls import url
from . import view
urlpatterns = [
    url(r'^hello$', view.hello),
]

访问app的地址就可查看效果:127.0.0.1:8080/hello

猜你喜欢

转载自blog.csdn.net/marslover521/article/details/68944417