python Flask框架学习——宏和import

宏和python中的函数类似,可以传参,但是没有返回值

格式:

{% macro 宏名(参数) %}
{% endmacro %}

应用

定义一个宏,功能 -> 用户名输入框和密码输入框

html文件

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

python文件

from flask import Flask, render_template

app = Flask(__name__)


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


@app.route('/macro/')
def macro():
    content = {
    
    
        'name': '用户名',
        'password': '密码'
    }
    return render_template('macro.html', **content)


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

结果:
在这里插入图片描述

import语句

上面定义了一个宏,如果想在另一个html文件里用这个宏,可以通过import语句导入宏

  • 方法1
<!--导入-->
{% import 'macro.html' as macro with context %}
<!--调用-->
{
   
   { macro.input(name, password) }}
  • 方法2
<!--导入-->
{% from 'macro.html' import input with context%}
<!--调用-->
{
   
   { input(name, password) }}

另外需要注意的是,导入模板并不会把当前上下文中的变量添加到被导入的模板中,如果你想要导入一个需要访问当前上下文变量的宏,有两种方法

  • 显式地传入请求或请求对象的属性作为宏的参数
  • 与上下文一起(with context)导入宏

与上下文中一起(with context)导入的方式

{% import 'macro.html' as macro with context %}
{% from 'macro.html' import input with context%}

猜你喜欢

转载自blog.csdn.net/weixin_44604586/article/details/109158561