栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【Django】模板应用

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Django】模板应用

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

模板介绍

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

建立模板 模板文件
makdir templates
vim templatges/first.html

{{ hello }}

其中 {{ 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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/829131.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号