【Django】模板应用

【Django】模板应用,第1张

目录
  • 模板介绍
  • 建立模板
    • 模板文件
    • 声明模板文件路径
  • 编写代码使用模板
  • 配置访问路径
  • 结果

模板介绍

上文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

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/743219.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-29
下一篇2022-04-29

发表评论

登录后才能评论

评论列表(0条)

    保存