• flask的宏 macro


    1、把它看作jinja2的一个函数,这个函数可以返回一个html字符串

    2、目的:代码可以复用,避免代码冗余

    定义的两种方式:

    1、在模版中直接定义:类似于macro1.html中定义方式

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>宏的定义</title>
    </head>
    <body>
    {#定义宏#}
    {% macro form(action,value='登陆',method='post') %}
    
        <form action="{{ action }}" method={{ method }}>
            <input type="text" placeholder="用户名" name="username">
            <input type="password" placeholder="密码" name="password">
            <input type="submit" value="{{ value }}">
        </form>
    
    {% endmacro %}
    
    {#调用宏#}
    {{ form('/') }}
    
    </body>
    </html>

     2、将所有的宏提取到一个模版中macro.html,导入方法:

    {% import 'macro.html' as xxx %}

    {{ xxx.宏名字(参数) }}

    macro/macro.html 定义宏的模版

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>宏的定义</title>
    </head>
    <body>
    {#定义宏#}
    {% macro form(action,value='登陆',method='post') %}
    
        <form action="{{ action }}" method={{ method }}>
            <input type="text" placeholder="用户名" name="username">
            <input type="password" placeholder="密码" name="password">
            <input type="submit" value="{{ value }}">
        </form>
    
    {% endmacro %}
    
    </body>
    </html>

    macro/macro2.html 调用宏

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>宏的使用2</title>
    </head>
    <body>
    {% import 'macro/macro.html' as macro with context %}
    {{ macro.form('/',value='注册') }}
    </body>
    </html>

     3、声明变量的方法

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>宏的使用2</title>
    </head>
    <body>
    
    {% set username = 'zhansan' %}
    {{ username }}
    
    {% with num=1000  %}
        {{ num }}
    {% endwith %}
    
    </body>
    </html>

    总结:

    变量:{{ 变量 }}

    块:

    {% if 条件 %}......{% endif %}

    {% for 条件 %}......{% endfor %}

    {% block 条件 %}......{% endblock %}

    {% macro 条件 %}......{% endmacro %}

    {% include '' %} 包含

    {% import '' %} 导入宏

    {% extends '' %} 模版继承

    {{ url_for('static',filename=' ')}} 导入静态文件

    {{ macro_name(xxx) }} 调用宏

    view:

    @app.route('/',endpoint='',methods=['GET','POST'])

    def index():

        直接使用request

        return response| ' ' |render_template('xxx.html')

    template:

       模版语法

  • 相关阅读:
    [PHP] thinkphp5 单入口多个模块绑定和路由开关
    [高并发]幂等性、最终一致性
    [高并发]Beanstalkd消息中间件使用
    [高并发]Redis 集群搭建步骤
    [PHP] laravel5.5 搭建流程
    [PHP] 破Laravel白屏问题
    talk 64
    linux
    yum
    linux修改时区
  • 原文地址:https://www.cnblogs.com/fat-girl-spring/p/15264428.html
Copyright © 2020-2023  润新知