母板和继承
母版
-
html页面,提取多个页面的公共部分
-
定义多个block块,需要让子页面进行填充
<head>
{% block page-css %} {% endblock %}
</head>
<body>
<h1>这是母板的标题</h1>
{% block page-main %} # 设置block块,可以在模板中进行个性化设置
{% endblock %}
<h1>母板底部内容</h1>
{% block page-js %}
{% endblock %}
</body>
继承
-
在模板的左上方写上
{% extends '母板文件名' %}
-
重写block块 ,写在block内部
-
块block
{% extends 'home.html'%}
{% block page-main %}
<p>《叽叽喳喳的世界》</p>
<p>作者:叽叽喳喳</p>
{% endblock %}
注意
-
{% extends ‘base.html’ %} 带上引号 不带的话会当做变量
-
{% extends ‘base.html’ %} 上面不要写其他内容
-
要显示的内容写在block块中
-
母板定义多个block 用于定义 css 或者 js
组件
可以将常用的页面内容如导航条,页尾信息等不会已经写完不会经常更改的组件保存在单独的文件中,然后在需要使用的地方按如下语法导入即可。
{% include '组件模板' %}
静态文件相关
静态文件引入
引用CSS
{% load static %}
<link rel="stylesheet" href="{% static 'css/dashboard.css' %}" rel="external nofollow" >
引用JS
{% load static %}
<script src="{% static "mytest.js" %}"></script>
引用图片
{% load static %}
<img src="{% static "images/hi.jpg" %}" alt="Hi!" />
某个文件多处被用到可以存为一个变量
{% load static %}
{% static "images/hi.jpg" as myphoto %}
<img src="{{ myphoto }}"></img>
使用get_static_prefix
# 方式一
{% load static %}
<img src="{% get_static_prefix %}images/hi.jpg" alt="Hi!" />
# 方式二
{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
<img src="{{ STATIC_PREFIX }}images/hi.jpg" alt="Hi!" />
<img src="{{ STATIC_PREFIX }}images/hi2.jpg" alt="Hello!" />
自定义simpletag
和自定义filter类似,只不过接收更灵活的参数。
定义注册simple_tag
@register.simple_tag(name="plus") # 可以省略(name="plus")
def plus(a, b, c):
return f"{a} + {b} + {c}"
使用自定义simple_tag
{% load tag %} #(load 文件名)即可
{% plus "1" "2" "abc" %}
【与filter的区别】
-
filter是过滤器,simple_tag是标签
-
filter最多传入两个参数
inclusion_tag
多用于返回html代码片段
templatetags/my_inclusion.py设计功能
from django import template
register = template.Library()
@register.inclusion_tag('page.html') # 结合的是page.html模板
def page(num):
return {'num':range(1,num+1)} # 返回必须是一个字典
templates/page.html进行组件设计
# page模板中存放的是一个分页组件
<nav aria-label="Page navigation">
<ul class="pagination">
<li>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li> {% for i in num %}
<li>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{ i }}</a>
</li>
{% endfor %}
<li>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
templates/jjzz.html中进行调用
<body>
{% load my_inclusion %}
{% page 5 %}
</body>
</html>