Jinja2 (template文件夹)

from flask import Flask, render_templateapp = Flask(__name__)@app.route('/about')def about():return render_template("about.html")@app.route('/')def index():return "hello"if __name__ == '__main__':app.run(debug=True) # app启动
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title></head><body><h1>Hello World Jinja2</h1></body></html>
更改模板文件夹
模板传递信息
在HTML中使用两个花括号来代表变量。再在代码中传参数
from flask import Flask, render_templateapp = Flask(__name__)@app.route('/about')def about():context = {"name": "hello user"}return render_template("about.html", **context)@app.route('/')def index():return "hello"if __name__ == '__main__':app.run(debug=True) # app启动
过滤器
length
<h1>Hello World {{ username|length }}</h1>
Join
官网
http://www.pythondoc.com/flask/
控制语句
if - else
@app.route('/control')def about():context = {"age": 10,}return render_template("control.html", **context)
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>CONTROL</title></head><body>{% if age > 18 %}<div>已经成年</div>{% else %}<div>未成年</div>{% endif %}</body></html>
for

from flask import Flask, render_templateapp = Flask(__name__)@app.route('/control')def about():context = {"age": 10,"books":["条目1", "条目2"],"person": {"name": "hangman", "age": 18}}return render_template("control.html", **context)@app.route('/')def index():return "hello"if __name__ == '__main__':app.run(debug=True) # app启动
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>CONTROL</title></head><body>{% if age > 18 %}<div>已经成年</div>{% else %}<div>未成年</div>{% endif %}{% for book in books %}<li>{{ book }}</li>{% endfor %}{% for key,value in person.items() %}<div>{{ key }} : {{ value }}</div>{% endfor %}</body></html>
继承
一般来说一个网站的header,footer都是固定的,这样就可以让基础模板写好这些通用的部分,在用继承基础来定制不同的类型。
父类
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>{% block title %}{% endblock %}</title></head><body><div>导航条</div>{% block body %}{% endblock %}<div>底部</div></body></html>
继承子类
{% extends "base.html"%}{% block title %}主页标题{% endblock %}{% block body %}主页首页{% endblock %}
继承静态文件
{% extends "base.html"%}{% block title %}主页标题{% endblock %}{% block head %}<link rel="stylesheet" href="{{ url_for('static',filename='css/main.css') }}">{% endblock %}{% block body %}<h1>首页</h1>{% endblock %}
