flask之宏和import语句

  • 宏的定义与使用场景:模板中的宏跟python中的函数类似,可以传递参数,但是不能有返回值,可以将一些经常用到的代码片段放到宏中,然后把一些不固定的值抽取出来当成一个变量
  • import 与python一样,通过import调用宏,调用其中的函数方法
    例子:
{% macro input(name, value='', type='text') %}
    <input type="{
     
     { type }}" name="{
     
     { name }}" value="{
     
     { value }}">
{% endmacro %}

在定义宏之后,可以在本程序中import该宏,导入方式:

{% import 'macro.html' as macro  %}
或者:
{% from "macro.html" import input %}

上代码:
HTML文件:
宏文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% macro input(name,value='',type='text') %}
    <input type="{
   
   { type }}",name="{
   
   { username }}",value="{
   
   { value }}">
    {% endmacro %}
<!--    <table>-->
<!--    <tr>-->
<!--        <td>用户名:</td>-->
<!--        <td>{
    
    { input('username') }}</td>-->
<!--    </tr>-->

<!--    <tr>-->
<!--        <td>密码:</td>-->
<!--        <td>{
    
    { input('password', type='password') }}</td>-->
<!--    </tr>-->
<!--    </table>-->
</body>
</html>
  • 注:可以把注释代码取消,此时可以显示一个表
    主HTML:导入和使用macro中定义的宏
{% import 'macro.html' as macro with context %}
{% from 'macro.html' import input %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>{
   
   { input('password', type='password') }}</p>
    <p>{
   
   { macro.input('username') }}</p>
</body>
</html>

python文件:

#! C:\Python\Python36
# -*- coding: utf-8 -*-
# @Time : 2020/10/16 13:58
# @Author : liuchengyong
# @File : 宏.py
# @Software: PyCharm
from flask import Flask,render_template
#from datetime import datetime

app = Flask(__name__)
context = {
    
    
    'username':'lcy1992',
    'age':18,
    'books':['python','java','php'],
    'book2':{
    
    'python':666,
            'java':777,
            'php':888}
}

@app.route('/macro/')
def if_for():
    return render_template('macro.html')

@app.route('/')
def import_test():
    return render_template('import_test.html')

if __name__ == '__main__':
    app.run(debug=True)

猜你喜欢

转载自blog.csdn.net/LCY133/article/details/109116611