- 创建项目
2 在views 里进行设置
from django.shortcuts import render
from django.http import HttpResponse
import datetime
# Create your views here.
class People(object):
def __init__(self, name, age):
self.name = name
self.age = age
def index(request):
p = People('小明', 9)
newTime = datetime.datetime.now()
content = {
'name': '张三',
'font_list': ['吃饭', '睡觉', '玩手机', '看视频', '扯淡'],
'study_list': ['c', 'HTML', 'JS', 'Python', 'Node', 'UI'],
'friend': p,
'today': newTime,
'girl_friend': {
'name': '小美',
'height': '160',
'hasKuang': True
}
}
return render(request, 'index.html', content)
3 配置urls 里的文件
4 在根目录下新建一个文件夹: templates 在该文件夹里新建一个html文件,如下图
5在settings 里进行设置
完成如下图:
render渲染html文件的时候 会从项目当中的templates里面找,所以无需设置templates路径
如果app的templates里面有和项目的templates里的文件重名的时候
只需在app里面新建一个文件夹 然后将重名的文件放入进去
渲染文件时跟上新建的文件夹路径即可
我们在这里进行如下操作:
可以在myApp文件里新建一个文件夹templates, 在该文件夹下新建一个文件夹templ, 在该文件夹下新建文件 index.html ,
现在进行一些高级设置
首先在myApp文件夹里新建一个文件夹:templatetags 在该文件夹里新建两个文件,一个init.py ,另一个test.py 在test.py 文件里进行如下配置
from django.template import Library
# 注册当前的数据 注册完以后必须重新 否则程序可能会崩溃
register = Library()
# 注册过滤器
@register.filter
def add(value):
pass
再次回到templates 文件夹的index.html 文件,进行如下配置
{% load test %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>hello world</h1>
<h1>现在显示的是{{name}}的信息</h1>
<h2>显示的时间是{{today | date:'Y-m-d h:i:s'}}</h2>
<h2>name={{friend.name}} age={{friend.age}}</h2>
</body>
</html>
重启服务器!!!
刷新页面后,可以看到如下图所示
其中:
{# 注释 #}: 表示注释
{{ XXX }} :获取XXX变量的值
条件判断(还是写在index.html 文件里面):
{# {% %} 用来进行条件判断以及循环 #}
{% if friend.age < 50 %}
<h3>{{friend.name}}年龄小于50岁</h3>
{% elif friend.age < 100 %}
<h3>{{friend.age}}小于100岁</h3>
{% else %}
<h3>{{friend.name}}超出年龄范围</h3>
{% endif%}
判断是否存在:
{# 判断p是否存在 #}
{%if p %}
<h3>有p对象</h3>
{% endif %}
{%if friend %}
<h3>有friend 对象</h3>
{% endif%}
列表输出与循环
<ul>
<li>{{font_list.0}}</li>
<li>{{font_list.1}}</li>
<li>{{font_list.2}}</li>
<li>{{font_list.3}}</li>
<li>{{font_list.4}}</li>
</ul>
<ul>
{% for font in font_list %}
<li>我的爱好是{{font}}</li>
{% endfor%}
</ul>
过滤器:
其中 upper 也可以变为 lower
<ul>
{% for study in study_list %}
<!--|过滤器-->
<li>学习内容{{study | upper}}</li>
{% endfor %}
</ul>
实现翻转:
<ul>
{% for font in font_list reversed %}
<li>{{font}}</li>
{% endfor %}
</ul>
循环输出:
<ul>
{% for study in study_list %}
{% if forloop.first %}
<h2>循环开始了</h2>
{% endif %}
<li>循环的内容:{{study}}</li>
{% if forloop.last %}
<h2>循环要结束了</h2>
{%endif%}
{% endfor %}
</ul>
循环输出索引 和 取值
<ul>
{% for study in study_list %}
{# forloop.counter获取数据索引 revcounter相反索引#}
<li>{{forloop.revcounter}}</li>
{% endfor %}
</ul>
<h2>{{girl_friend.name}}</h2>