FLASK学习记录-宏、模板继承
宏
{% macro name %}
{% endmacro %}
app.py
from flask import Flask,render_template app = Flask(__name__) @app.route('/') def index1(): return render_template("macro1.html") @app.route("/") def index2(): return render_template("macro2.html") if __name__ == '__main__': app.run(host='0.0.0.0',port=8000,debug=True)
{# 求和 #} <body> {% macro add( ) %} <p> {% set sum=namespace(num=0) %} {% for i in range(0,varargs|length) %} {% set sum.num=sum.num+varargs[i] %} {% endfor %} {{ sum.num }} </p> {% endmacro %} {{ add(10,20) }} {{ add(30,50,90) }} </body> {# 宏导入 #} {% macro input(name,type='text',value='' ) %} <input type="{{ type }}" name="{{ name }}" value="{{ value }}"> {% endmacro %} <body> {% from 'macro.html' import input %} <p>用户名:{{ input("username") }}</p> <p>密码:{{ input("pwd",type="password") }}</p> <p>{{ input("login",type="submit",value="登录") }} {{ input("clear",type="reset",value="清空") }}</p> </body>
加载CSS, favicon.icon, JavaScript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="{{ url_for('static',filename='css/test.css') }}"> <link rel="stylesheet" href="static/css/test.css"> <link rel="icon" href="{{ url_for('static',filename='favicon.ico') }}"> </head> <body> <p>css外部静态文件引用</p> <img src="{{ url_for('static',filename='images/test.jpg') }}"> <script src="{{ url_for('static',filename='javascript/test.js')}}"></script> </body> </html>
模板继承
{# 父模板 #}
{% block blockName %}
{% endblock %}
{# 子模板 #}
{% extends parent_blockName %}