Flask015_宏和 import 语句
- 宏 forms.html
1 {% macro input(name, value="",type="text") %} 2 <input type="{{ type }}" value="{{ value | escape }}" name="{{ name }}"> 3 {% endmacro %} 4 5 {% macro textarea(name, value="", rows=10, cols=40) %} 6 <textarea name="{{ name }}" rows="{{ rows }}" cols="{{ cols }}"> 7 {{ value | escape }} 8 </textarea> 9 {% endmacro %}
- 宏使用 index.html
1 {% from 'forms.html' import input as input_field %} 2 {% from 'forms.html' import textarea as textarea_field %} 3 <!DOCTYPE html> 4 <html lang="en"> 5 6 <head> 7 <meta charset="UTF-8"> 8 <title>宏和 import 语句</title> 9 </head> 10 11 <body> 12 <dl> 13 <dt>Username</dt> 14 <dd>{{ input_field('username') }}</dd> 15 <dt>Password</dt> 16 <dd>{{ input_field('password', type="password")}}</dd> 17 </dl> 18 <p> 19 {{textarea_field("comment")}} 20 </p> 21 </body> 22 23 </html>
- 模板调用
1 @app.route("/") 2 def index(): 3 return render_template("index.html")
- 效果