【Django】模板应用

模板介绍

上文helloworld中,我们是直接将hello world以文本的方式通过django.http.HttpResponse传到http访问response中,这样我们将视图与数据混合到了一起,并不方便维护代码,所以建议采用模板的方式,将视图与数据分离开来。

建立模板

模板文件

makdir templates
vim templatges/first.html
<h1>{
   
   { hello }}</h1>

其中 { { hello }} 是变量, 用双大括号可以引用一个变量

声明模板文件路径

在hellowold/settings.py的’DIRS’中加入templates的路径,添加方式如下图
需要注意是否以及引用os库,如果没有引用需要额外添加

import os

在这里插入图片描述

编写代码使用模板

vim helloworld/view.py
from django.shortcuts import render
def hello2(request):
    context = dict()
    context['hello'] = 'Hello World!'
    return render(request, 'first.html', context)

配置访问路径

path(r'hello2/', view.hello2),

在这里插入图片描述

结果

python manage.py runserver

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_34954047/article/details/124293194