Django 模板系统
视图函数不适合编辑html代码,可以编写完html文件后通过django模板系统更视图结合读取展示数据
基本语法-在html中使用
- 变量:{{变量名}}
- for循环标签:开始标签:{% for 获取列表数据变量名 in 列表变量名%},结束标签:{%endfor%}
- if-else分支标签:{% if %},{% else %},{% endif%}
django调用模板并传递数据
在views.py视图文件中添加方法返回模板文件
django默认会先从项目的template文件夹中查找对应的文件,没有在通过应用的template中查找文件,再全局搜索。
from django.shortcuts import render
from .models import Article
def get_index(request):
# 读取所有文章列表
articleList = Article.objects.all()
# 返回在template文件夹中的index.html模板文件,并传递名称为articleList的数据
return render(request, 'blog/index.html', {'articleList': articleList})
django模板读取传递的数据
<div class="col-md-9" role="main">
<div class="body-main">
# 循环读取articleList的数据并赋值给article变量
{% for article in articleList %}
<div>
# 读取article变量中的title属性
<h2>article.title</h2>
# 读取article变量中的brief_content属性
<p> article.brief_content</p>
</div>
{% endfor %}
</div>
</div>
<div class="col-md-3" role="complementary">
<h2> 最新文章</h2>
{% for article in articleList %}
<h4><a href="#"> article.title</a></h4>
{% endfor %}
</div>
修改django读取模板设置
打开django_introduction文件夹下的setting.py文件
找到TEMPLATES数组,修改里面的DIRS数组添加os.path.join(BASE_DIR, ‘模板所在的文件夹’)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, '/blog/templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]