过滤器:
处理变量,把原始的变量经过处理后展示出来。作用的对象是变量。
语法
{{ avater|defulat(‘xxx’) }}
如果在主文件夹中,没有指定avatar的值,则可以在index.html中进行指定。
length过滤器
求列表/字符串/元组的长度。
示例:
python.py
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def index():
connents = [
{
'user':u'徐',
'content':'xxxx'
},
{
'user': u'sweet',
'content': 'xxxx'
}
]
return render_template('index.html', connents=connents)
if __name__ == '__main__':
app.run(debug=True)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<img src="{{ avatar|default("http://gitbook.cn/gitchat/activity/58e47b6dc59d53926e61186b") }}" alt="">
<hr>
<p>评论数:({{ connents|length }})</p>
<ul>
{% for connent in connents %}
<li>
<a href="#">{{ connent.user }}</a>
<p>{{ connent.content }}</p>
</li>
{% endfor %}
</ul>
</body>
</html>
继承
继承的作用:可以把一些公共的代码放在父模板中,避免每个模板写同样的代码
语法:
{% extends ‘base.html’ %} base.html为父模板的名称
block实现
作用:可以让子模版实现一些自己的需求。父模板需要提前定义好。
注意:子模版的代码,必须放在block块中。
示例:
python.py
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login/')
def login():
return render_template('login.html')
if __name__ == '__main__':
app.run(debug=True)
base.html 父模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
<style>
.nav{
background: #3a3a3a;
height: 65px;
}
ul{
overflow: hidden;
}
ul li{
float: left;
list-style: none;
padding: 0 10px;
line-height: 65px;
}
ul li a{
color: #ffffff;
}
</style>
</head>
<body>
<div class="nav">
<ul>
<li><a herf="#">首页</a></li>
<li><a herf="#">发布问答</a></li>
</ul>
</div>
{% block main %} #为导航条下面的内容做接口
{% endblock %}
</body>
</html>
index.html 子模板
{% extends 'base.html' %}
{% block title %}
首页
{% endblock %}
{% block main %}
<h1>这是首页</h1>
{% endblock %}
login.html 子模板
{% extends 'base.html' %}
{% block title %}
登陆
{% endblock %}
{% block main %}
<h1>这是登陆页面</h1>a
{% endblock %}