模板
将应用learn加入到setting.py中的INSTALLED_APPS中
INSTALLED_APPS = [
# 'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
'learn',
]
打开learn/views.py写一个首页的视图
# coding:utf-8
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
learn下新建模板目录templates,在templates下创建index.html文件
<!DOCTYPE html>
<html>
<head>
<title>欢迎学习django</title>
</head>
<body>
aaaaaaaaaaaaaaaa
</body>
</html>
页面展示
Paste_Image.png传递参数,修改views.py,修改部分如下:
def index(request):
content = '欢迎欢迎,热烈欢迎'
return render(request,'index.html',{'content':content})
修改模板index.html ,修改部分如下:
<body>
{{ content }}
</body>
页面展示
Paste_Image.png模板中的循环、条件判断、过滤器等请参考下一节
补充
⽹站模板的设计,⼀般的,我们做⽹站有⼀些通⽤的部分,⽐如 导航,底部,访问统计代码等等 nav.html, bottom.html, tongji.html
可以写一个base.html来包含这些通用文件(include)
代码如下:
###view.py文件
# coding:utf-8
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index(request):
title = '欢迎登陆'
content = '欢迎欢迎,热烈欢迎'
return render(request,'learn/index.html',{'title':title,'content':content})
Paste_Image.png模板目录结构
模板html代码
<!-- base.html文件 -->
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{{ title }}{% endblock %}</title>
</head>
<body>
{% include 'public/nav.html' %}
{% block content%}
<div>这是默认内容</div>
{% endblock %}
{% include 'public/button.html' %}
{% include 'public/tongji.html' %}
</body>
</html>
<!-- index.html文件 -->
{% extends 'public/base.html' %}
{% block title %}{{ title }}{% endblock %}
{% block content %}
{% include 'public/ads.html' %}
<div>{{ content }}</div>
{% endblock %}
<!-- 其余几个文件都为空,暂无内容 -->
Paste_Image.png页面展示
网友评论