首页
仓库
文档
nginx手册
Docker手册
workerman
Flask
PHP
python
RabbitMQ
其他
Linux
占位1
占位2
目录
###响应模板 from flask import Flask, render_template 略 return render_template('index.html', id=123) 在默认模板目录下寻找文件 return render_template('index/2.html', id=123) 多级目录下寻找 return render_template('index/2.html', id=123) ###模板变量显示 <h1>{{变量名}}</h1> ###条件 {% if name=='zs' %} 张三 {% elif name=='lis' %} 李四 {% else %} 王五 {% endif %} ###循环 <ul> {% for item in list %} <li>序号:{{ loop.index }} <a href="{{ item.href }}">{{ item.caption }}</a></li> {% else %} 无数据 {% endfor %} </ul> ###嵌套循环 ```python <ul> {% for item in list %} <li><a href="{{ item.href }}">{{ item.caption }}</a></li> {% for item2 in item.list %} <li>-->{{ item2.caption }}</li> {% endfor %} {% endfor %} </ul> ``` ###内置过滤器 {{username|reverse|upper}} 翻转,大写 ###引入模板 {% include 'index/nav.html' %} #默认也是在模板根目录寻找 ###模板中定义变量 {% set name='李四' %} #也可以修改已有变量的值 #定于局域变量,不影响全局 {% with %} {% set name2='李四2' %} {{name2}} {% endwith %} ###模板继承 ```python 创建父模板 <!doctype html> <html> <head> <meta charset="utf-8"> <title>demo</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://db.tolog.cn/demo/timestamp/css/bulma.css"> </head> <body> <div class="container"> <section class="hero is-primary"> <div class="hero-body"> <p class="title"> {% block title %} {% endblock %} </p> <p class="subtitle">没啥用 </p> </div> </section> {% include 'nav.html' %} <div class="box">{% block body %} {% endblock %}</div> {% include 'footer.html' %} </div> </body> </html> ``` 子模板 ```python {% extends 'base.html' %} 继承模板 {% block title %}我就试试{% endblock %} {% block body %} {% if gender!='male' %} Mr. {% else %} Ms. {% endif %}</h1> <h2> {{username|reverse|upper}}你正在使用flask</h2> {# 用来写注释 #} <img src="/static/5.png"> <ul > {% for item in list %} <li><a href="{{ item.href }}">{{ item.caption }}</a></li> {% endfor %} </ul> <div> 当前网页:{{request.url}} </div> {% endblock %} ``` ###加载静态文件 ```python <link rel="stylesheet" href="/static/css/bulma.css"> #写死的地址 <link rel="stylesheet" href="{{url_for('static',filename='css/bulma.css')}}"> #动态地址 ``` ###全局转义 默认是对html,htm,xml,xhtml的模板渲染全局转义 设置不转义{{str|safe}} app.jinja_env.autoescape=Flase #设置全局不转义 (危) 设置转义{{str|escape}} ###全局函数 默认好像就有个全局函数,url_for,range,lipsum, ###自定义全局函数 ```python @app.template_global() def hello(name): return '你好,'+name; # 模板中 {{hello(name2)}} ``` ###闪现消息 原理是用的session,需要配置app.config['SECRET_KEY'] ='sdasdasdasdsadasd' flash('消息1') #插入消息 flash('消息2') 可以在用户下一次请求的时候使用get_flashed_messages() 获取,仅能获取一次 就像一次性session 没啥大用吧。。