我们在制作网页的时候通常有很多公共地方可以单独写入一个文件,然后在其他文件中引用,那么flask中对这种需要反复引用文件的方法有多种多中方案,其中有include,extends这两种
1.include
使用方式一般都是公共头和尾分开写到header.html和footer.html文件内
然后在主体文件中include这两个文件到指定位置即可,例如index.html文件
{% include "header.html" %}
<div class="warp">
这里是网页主体...
</div>
{% include "footer.html" %}上面的例子就能看出很简单,基本和其他语言框架也是差不多用法
2.extends
使用这种方式我们一般都需要创建一个基础模板,例如我创建的是layout.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<meta http-equiv="Cache-Control" content="no-transform"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta http-equiv="Content-Language" content="zh-CN" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='layui/css/layui.css') }}" />
<link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/index.css') }}" />
<script src="{{ url_for('static', filename='layui/layui.js') }}"></script>
<body>
{% block content %}
{% endblock %}
{% block test %}
这是父模板的内容
{% endblock%}
</body>
</html>然后在子模板中继承和填充block标记,例如我的index.html文件就是这样
{% extends "web/layout.html" %}
{% block title %}
苏老博客
{% endblock %}
{% block content %}
<p style="color:red">这是是主体内容</p>
{% endblock %}
{% block test %}
{{ super() }}
{% endblock %}其中super()是用来调用父模板中标记块的内容的方法

内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:https://sulao.cn/post/661
评论列表