基本数据类型的渲染
# views.py文件
def test(request):
name = 'nick'
age = 18
hobby = ['read','music','sing']
info = {"name":'nick',"age":18,"hobby":['read','music','sing']}
users = [{"name":'nick',"age":18},{'name':'egon',"age":20},{"name":"sean","age":19}]
return render(request,'test.html',{'name':name,"age":age,"hobby":hobby,"info":info,"users":users})
# test.html文件
name:{{ name }}<br> # 字符串类型渲染
age:{{ age }}<br> # 数字类型渲染
# 列表类型渲染
<ul>
<li>{{ hobby.0 }}</li>
<li>{{ hobby.1 }}</li>
<li>{{ hobby.2 }}</li>
</ul>
<ul>
{% for item in hobby %}
<li>{{ item }}</li>
{% endfor %}
</ul>
# 字典类型渲染
<ul>
<li>{{ info.name }}</li>
<li>{{ info.age }}</li>
<li>{{ info.hobby }}</li>
</ul>
<ul>
{% for item in info.keys %}
<li>{{ item }}</li>
{% endfor %}
</ul>
<ul>
{% for item in info.values %}
<li>{{ item }}</li>
{% endfor %}
</ul>
<ul>
{% for key,val in info.items %}
<li>{{ key }}:{{ val }}</li>
{% endfor %}
</ul>
# 列表套字典
{% for user in users %}
{{ user.name }}
{% endfor %}
母版与子版
在开发过程中,将每个页面都有样式写在一个母版里,在子版中继承使用
# 母版loyout.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
{% block mycss %}
{% endblock %}
</head>
<body>
{% block mycontent %}
{% endblock %}
</body>
{% block myjs %}
{% endblock %}
</html>
# 子版test.html
{% extends 'loyout.html' %}
{% block mycss %}
子版自定制的样式
{% endblock %}
{% block mycontent %}
子版自定制的内容
{% endblock %}
{% block myjs %}
子版自定制的js
{% endblock %}
导入模块
在python中可以将功能写成一个模块,在多个py文件中用import导入;同理,在django中也可以将好的页面或组件写成模块,在多个文件中用include导入使用.如
# test.html模块文件
<form action="" method="post">
用户名:<input type="text">
密码:<input type="password">
<input type="submit" value="提交">
</form>
# 在test1.html中导入test.html中的模块
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
{% include 'test.html' %}
{% include 'test.html' %}
{% include 'test.html' %}
{% include 'test.html' %}
</body>
</html>
与python导入模块不同,在python中只能导入一次,在django中可以导入多次,导入几次就显示几个
内置函数
# name是后端返回的字符串
{{ name|upper }} {# 大写 #}
{{ name|lower }} {# 大写 #}
{{ name|first|upper }} {# 取首字母,变大写 #}
{{ name|truncatewords:"2"}} {# 取name中前两个单词#}
自定义函数
步骤一:在app中创建templatetags目录
步骤二:在templatetags目录中创建任意.py文件,如user.py,在文件中自定义函数
from django import template
register = template.Library()
@register.filter
def my_filter(val, args):
return val + args
@register.simple_tag
def my_upper(val, args, args1):
return val + args + args1
步骤三:在html中调用函数
{%load user %}
{# simple_filter #}
{{name | my_filter:'xxx'}}
{# simple_tag #}
{%my_upper "zekai" "sss" 'dsadsadsa'%}
filter函数只能传入两个参数,simple_filter函数可以传多个参数