【Django 学习笔记】4、模板

admin 2023年5月15日09:41:30评论23 views字数 984阅读3分16秒阅读模式
上一节视图使用django.http.HttpResponse()来向页面返回内容,但是这样不符合 Django 的 MVT 思想,所以这一节将来记录 Django 模板的应用。
模板是一个文本,用于分离文档的表现形式和内容。

1、在项目根目录下,创建templates目录,在templates下新建index.html文件,PyCharm将自动生成html的文件内容格式。

.├── Book├── BookManager└── templates    └── index.html


2、编辑setting.py文件第58行,修改TEMPLATES内容如下,目的是添加templates路径,好让接下来程序能够找到index.html文件。

'DIRS': [os.path.join(BASE_DIR,'templates')],

3、修改view.py文件如下。

from django.shortcuts import renderfrom django.http import HttpResponse
def index(request): context={ 'H1':'OK!', 'H2':'-- By TeamsSix' } return render(request,'index.html',context)

4、修改index.html文件如下。

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Home</title></head><body><H1 style="color:red;">{{ H1 }}</H1><H2 style="color:limegreen;">{{ H2 }}</H2></body></html>

5、此时,刷新浏览器。

【Django 学习笔记】4、模板

6、视图与templates的总结


【Django 学习笔记】4、模板

原文链接:https://www.teamssix.com/year/200301-182831.html

参考链接:

https://www.runoob.com/django/django-template.html

往期推荐

Django 学习笔记 | 1、基础概念和MVT架构

Django 学习笔记 | 2、模型

Django 学习笔记 | 3、视图


【Django 学习笔记】4、模板

原文始发于微信公众号(TeamsSix):【Django 学习笔记】4、模板

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2023年5月15日09:41:30
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   【Django 学习笔记】4、模板https://cn-sec.com/archives/785598.html

发表评论

匿名网友 填写信息