- 模板语法(变量,标签,过滤器)
- 模板的继承-extends,包含-include,引用-self
- 模板的宏定义和使用,消息闪现
import os from datetime import datetime from flask import Flask, g, request,render_template_string, url_for, flash from flask import render_template,redirect mbapp = Flask(__name__) # 为模板引擎添加扩展支持break和continue mbapp.jinja_env.add_extension('jinja2.ext.loopcontrols') # session的安全机制,使用flash时需要设置该随机串 mbapp.secret_key = 'de42324' @mbapp.route('/') def index(): return '初步测试' @mbapp.route('/index') def index02(): # _external=True 打印出全路径,前一个参数是view # 使用url_for你想解析,可以避免route变动之后忘记更新 print('index',url_for('index',_external=True)) print('index02',url_for('index02')) print('special_symbols',url_for('special_symbols',_external=True)) return render_template('index.html') @mbapp.route('/hello') def helloworld(): '''把html文件内容在浏览器展示出来''' # return render_template('hello.html') hello_html = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hello</title> </head> <body> <h1>你好,欢迎你</h1> </body> </html>""" return render_template_string(hello_html) @mbapp.route('/hello02') def hello02(): # 基本数据类型渲染 age = 89 money = 90.87 name = 'mark' foods = {1:'苹果',2:'桔子','book':'java','test':{'name':'mark','age':89}} tuple_city = ('北京','上海','深圳') list_test = ['python','milk','girls',{ 'name':'小王','age':45,'like':'apple' }] return render_template('hello.html',age=age, money=money, name=name,foods=foods,tuple_city=tuple_city ,list_test=list_test)#数据传递 @mbapp.route('/show/html') def show_html(): '''浏览器渲染过程,没有模板怎么在浏览器上展示HTML''' # 1.拿到当前app所在路径,拼接成磁盘上html的全路径地址 file_name = os.path.join(os.getcwd(),'templates','index.html') # os.getcwd()也可以用os.path.dirname(__file__) print(file_name) # 2.读取html文件中的内容 now_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') with open(file_name,'r',encoding='utf-8') as f: html = f.read() # 3.替换html中的特殊字符({{time}}) html = html.replace('{{ time }}',now_time) # 4.将html的内容发送给浏览器 return html # return 'hello world,test0222,测试函数' @mbapp.before_request def g_test(): # 所有的视图都可以调用 g.user = 'zhangsan' @mbapp.route('/spe_sym') def special_symbols(): return render_template('spe_sym.html') # 上下文处理器,在模板上下文中添加新的内容(可以是变量也可以是函数) @mbapp.context_processor def inject_user(): return dict(user=g.user) # 查看url路由规则 print(mbapp.url_map) @mbapp.errorhandler(403) def forbidden_page(err): """403错误提示:你没有权限访问页面""" print(err) return '你没有权限访问页面,请联系管理员开通权限' @mbapp.route('/tag') def tag(): """模板标签的使用""" var = 0 a = 4 list_user = [{'name':'xiaowang','like':'apple','hate':'香蕉'}, {'name':'xiaowang','age':34}, {'name': 'lily', 'like': '香蕉', 'hate': '西瓜'}, {'name': 'lily', 'age': 90} ] # list_user= [] return render_template('tag.html',var=var,a=a, list_user=list_user) @mbapp.route('/use_filter') def use_filter(): """过滤器的使用""" wel = 'welcome,lily' var = '你好' #使用boolen类型 like = None html_value = '<h3>标题加粗,html代码转义测试</h3>' phone_num = '13456768907' return render_template('use_filter.html',wel=wel,var=var,like=like, html_value=html_value,phone_num=phone_num) @mbapp.template_filter('phone') def phone_format(phone_num): """自定义过滤器,完成电话号码脱敏处理""" # 13987657890 -> 139****7890 return phone_num[0:3] + '****' + phone_num[7::] # return phone_num[0:3] + '****' + phone_num[7:] @mbapp.route('/globalfunc') def global_func(): """模板全局函数的使用""" return render_template('global_func.html') @mbapp.route('/macro') def macro(): """模板中宏的使用""" return render_template('macro.html') @mbapp.route('/index_mk') def index_mk(): return render_template('index_mk.html') @mbapp.route('/coding_mk') def coding_mk(): return render_template('coding_mk.html') @mbapp.route('/article_mk') def article_mk(): article_context = 'article_context测试值' return render_template('article_mk.html',article_context=article_context) @mbapp.route('/wenda_mk') def wenda_mk(): wenda_context = 'wenda_context2222' return render_template('wenda_mk.html',wenda_context=wenda_context) # 用户登录成功之后跳转到个人中心页面 @mbapp.route('/mine') def mine(): return render_template('mine.html') @mbapp.route('/login', methods=['GET', 'POST']) def login(): """用户登录""" if request.method == 'POST': print('处理了登录部分') print(request.form) flash('登录成功','success') flash('登录失败', 'info') flash('密码错误','error') return redirect('/mine') # if request.form[0][0] != 'admin': # return redirect('/test') return render_template('login.html')
过滤器的使用
<h3>不使用过滤器</h3> <p>{{ wel }}</p> <h3>使用内置过滤器upper</h3> {{ wel|upper }} <h3>使用标签,过滤器</h3> <p> {% filter upper %} {{ wel }} {% endfilter%} </p> <h3>默认值default过滤器的使用</h3> <p>变量var:{{ var|d('默认为None') }}</p> 变量like:{{ like|default('我没有',True) }} <h3>HTML转义——过滤器的使用</h3> <!-- 因为html会自动转义,所以关闭自动转义tag来查看效果(源码中)--> {% autoescape false %} <p>直接引用:{{ html_value }}</p> <p>使用HTML转义escape过滤器:{{ html_value|e }}</p> {% endautoescape %} <h3>自定义过滤器phone的使用</h3> <p>phone_num脱敏后输出为:{{ phone_num|phone }}</p>
模板中宏的使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>模板中宏的使用</title> <style type="text/css"> .input-control{ border:2px solid #f00; } </style> </head> <body> <h3>模板中宏的使用</h3> <form action=""> {% macro input(name,type='text',value='') %} <div> <input class="input-control" type="{{ text }}" name="{{ name }}" value="{{ value }}"> </div> {% endmacro %} {# 调用宏实现 用户名 username #} {{ input('username',value='admin') }} {# 调用宏实现 密码 password #} {{ input('password',type='password',value='123456') }} {# 调用宏实现 年龄 age #} {{ input('age',type='int',value='30') }} <!-- <div> <input class="input-control" type="text" name="'username"> <input class="input-control" type="text" name="password"> <input class="input-control" type="number" name="age"> </div> --> </form> <!--宏的引用--> <h3>宏的引用,forms_macro.html 两种导入方式</h3> <h3>第一种导入方式</h3> {% import 'forms_macro.html' as fm %} <p>{{ fm.input02('one',value='one test') }}</p> <h3>第二种导入方式</h3> {% from 'forms_macro.html' import input02 %} <p>{{ input('two',value='two test') }}</p> </body> </html>
消息闪现
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>个人中心</title> <style type="text/css"> .success { color: #0f0; } .error { color: #f00; } </style> </head> <body> <h3>个人中心</h3> <h3>实现消息展现</h3> {% for category,message in get_flashed_messages(with_categories=true,category_filter=['error']) %} <p class="{{ category }}"> {{ category }}-{{ message }} </p> {% endfor %} </body> </html>
继承,包含和引用
{% extends 'base_mk.html' %} {% block title_text %} Luck问答系统 {% endblock %} {% block content %} <p>单属于问答的内容</p> <aside class="left"> 左侧内容区域--问答 <br> {{ self.title_text() }} </aside> <aside class="right"> 右侧内容区域--问答 {% include 'sidebar_mk.html' %} <p>{{ self.title_text() }}</p> </aside> {% endblock%}