zoukankan      html  css  js  c++  java
  • 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:

       模版语法

  • 相关阅读:
    perl中的默认变量与Z/map介绍
    perl6中字符串字母编历
    将数字转化为特殊符号的密码
    vue: axios
    vue: alias
    background-size
    问题:当浏览器窗口变化时,内容的大小以及相对位置也要相应变化
    vue移动端适配
    Web 端屏幕适配方案
    vue: register and import
  • 原文地址:https://www.cnblogs.com/fat-girl-spring/p/15264428.html
Copyright © 2011-2022 走看看