详解flask入门模板引擎


Posted in Python onJuly 18, 2018

模板引擎

说明:模板文件就是按照一定的规则书写的展示效果的HTML文件 模板引擎就是负责按照指定规则进行替换的工具

模板引擎选择jinja2

一、渲染模板的方法

1、将渲染的模板进行返回

render_template()

2、渲染字符串返回

render_templates_string()

实例

@app.route('/')
def index():
  #将模板内容响应给用户
  return render_template('index.html')
  #渲染一内容响应给用户
  return render_template_string('<h1 style="color:green;font-size:18px;">原谅色</h1>')

二、模板的语法

模板中只存在俩种语法

1、变量

{{ var }}

#像模板文件中传参
return render_template('index.html',title='首恶')
{{ title }}

2、标签

{% 标签名 %}

注意:

在模板中使用字典中的键 需要像使用对象得方式来调用

{{data.key}}

如果在模板中给定的变量不存在 则插入的是空字符串 不会报错

三、过滤器

过滤器使用管道符 | 来使用的

1、{{ var|abs }} 返回一个数值的绝对值

2、default 设置默认值

只有当给定的变量不存在时 则执行默认值

当设置default的boolean的时候 会执行默认值

<li>{{ data.bool|default('我是默认值',boolean=True) }}</li>

3、first: 取出变量中的第一个字符

4、last: 取出变量中的最后一个字符

5、format: 字符的格式化

<li>{{ '我叫%s 我今年%d岁了 我的存款为 %.2f'|format('罗铁汉',38,23) }}</li>

6、length: 返回变量值的长度

7、join: 拼接成字符串

<li>{{ [1,2,3,4]|join('') }}</li>
<li>{{ [1,2,3,4]|join('x') }}</li>

8、safe: 不转义标签 原样显示

9、lower 转为小写

10、upper 转为大写

11、replace 替换

<li>{{ data.string|replace('a','x') }}</li>

12、striptages 去除HTML标签

{{ data.html|striptags }}

四、标签

语法格式 :{% 标签名 %}

(1) if

实例

{% if data.bool %}
    <li>{{ data.bool }}值为真</li>
{% elif True %}
    <li>{{ True }}职位真</li>
{% else %}
    <li>{{ data.bool }}值为假</li>
{% endif %}

(2) for 循环

实例

{% for i in data.xxxx %}
{# 错误的迭代方法TypeError: 'bool' object is not iterable #}
{#  {% for i in data.bool %}#}
    <li>{{ i }}</li>
{% else %}
    <li>当迭代的变量不存在时 则执行else</li>
{% endfor %}

注意:

break continue 不能够在这里使用

迭代字典

{% for k,v in data.items() %}
   <li>{{ k }}=>{{ v }}</li>
{% endfor %}

获取当前迭代的状态

变量 描述
loop.index 获取当前迭代的索引 从1开始
loop.index0 获取当前迭代的索引 从0开始
loop.first 是否为第一次迭代
loop.last 是否为最后一次迭代
loop.length 迭代的长度

六、注释

{# 多行注释 #}

七、文件包含 include

相当于把一个文件 拷贝到当前的你的包含的位置

实例

{% include 'common/header.html' %}
<div>我是中间的内容</div>
{% include 'common/footer.html' %}

注意:

1、包含的公共的文件中 只存放 公共的代码 除此以外什么都不要存在

2、导入的时候 如果文件和在同一级别 直接导入就可以 如果包含在某个目录中 需要写出路径

{% include 'common/header.html' %}
{% include 'test.html' %}

八、宏 macro

概念: 类似python中的函数

实例

在macro.html中

{% macro input(name,type='text',value='') %}
  <input type="{{ type }}" name="{{ name }}" value="{{ value }}">
{% endmacro %}

宏的调用

{{ input('text','username','') }}
{{ input() }} 
{{ input(type='password',name='userpass') }}

宏的导入

(1) import

{% import 'test.html' as test %}
{% import 'common/test.html' as test %}
<p>用户名: {{ test.input(type='password',name='userpass') }}</p>

(2) form import

{% from 'test.html' import input %}
{% from 'common/test.html' import input %}
<p>用户名: {{ input(type='password',name='userpass') }}</p>

注意:

  1. 宏的调用只能在定义的下方去调用 否则未定义
  2. 宏如果存在形参 且没有默认值 则可以调用(没意义)
  3. 形参的默认值 需要遵循默认值规则 有默认值的参数 放右侧
  4. 可以正常使用 关键字参数

九、继承 extends

语法:

  1. {% extends %} 继承某个模板
  2. {% block %} 挖坑和填坑
  3. {{ super() }} 调用被替换掉的代码

base.html

<!DOCTYPE html>
<html lang="en">
<head>
{% block header %}
  <meta charset="UTF-8">
  {% block meta %}
  {% endblock %}
  <title>{% block title%}首页{% endblock %}</title>
  <style>
    {% block style %}
      p{color:red;}
    {% endblock %}
  </style>
  {% block link %}
  {% endblock %}
  {% block script %}
  {% endblock %}
{% endblock %}
</head>
<body>
<header>头部</header>
{% block con %}
  我是中间的内容部分
{% endblock %}
<footer>尾部</footer>
</body>
</html>

index.html继承 base.html

{% extends 'common/base.html' %}
{% block title %}
我的首页
{% endblock %}
{% block style %}
  {{ super() }}
  p{color:green;}
{% endblock %}
{% block con %}
<p>我是首页的内容</p>
  我是首页的内容
{% endblock %}

注意:

如果当替换某个样式的时候 所有原来的样式 都消失了 去查看是否使用了super()

十、flask-bootstrap

安装

pip install flask-bootstrap

sudo pip3 install flask-bootstrap

使用

继承 bootstrap/base.html 基础模板 改造成适用于自己网站的base.html基础模板

自己的base.html

{% extends 'bootstrap/base.html' %}
{% block navbar %}
  <nav class="navbar navbar-inverse" style="border-radius: 0px;">
    <div class="container-fluid">
      <!-- Brand and toggle get grouped for better mobile display -->
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
            data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span class="glyphicon glyphicon-signal" aria-hidden="true"></span></a>
      </div>

      <!-- Collect the nav links, forms, and other content for toggling -->
      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav">
          <li class="active"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >首页 <span class="sr-only">(current)</span></a></li>
          <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >发帖子</a></li>

        </ul>

        <ul class="nav navbar-nav navbar-right">
          <form class="navbar-form navbar-left">
          <div class="form-group">
            <input type="text" class="form-control" placeholder="Search">
          </div>
          <button type="submit" class="btn btn-default">Submit</button>
        </form>
          <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >注册</a></li>
          <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >登录</a></li>
          <li class="dropdown">
            <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
              aria-expanded="false">个人中心 <span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >个人信息</a></li>
              <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >修改头像</a></li>
              <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >修改密码</a></li>
              <li role="separator" class="divider"></li>
              <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Separated link</a></li>
              <li role="separator" class="divider"></li>
              <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >退出登录</a></li>
            </ul>
          </li>
        </ul>
      </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
  </nav>
{% endblock %}
{% block content %}
  <div class="container">
    {% block pagecontent %}
      网页的中间内容部分写在当前的位置
    {% endblock %}
  </div>
{% endblock %}

使用 index.html

{% extends 'common/base.html' %}
{% block title %}
首页
{% endblock %}

十一、错误页面的定制

manage.py

@app.errorhandler(404)
def page_not_found(e):
  return render_template('common/error.html',error=e,code=404)

@app.errorhandler(500)
def server_error(e):
  return render_template('common/error.html',error=e,code=500)
error.html
{% extends 'common/base.html' %}
{% block title %}
  {{ code }}错误
{% endblock %}
{% block pagecontent %}
  <div class="alert alert-danger" role="alert">{{ error }}</div>
{% endblock %}

十二、视图传递多个参数

(1) 原始传参

@app.route('/')
def index():
  return render_template('index.html',arg1=1,arg2=2...)

(2) 使用字典

@app.route('/')
def index():
  return render_template('index.html',arg={arg1:1,arg2:2...})
  kwarg={arg1:1,arg2:2...}
  return render_template('index.html',``)

(3) 使用全局变量g

@app.route('/')
def index():
  g.name = '张三'
  g.age = 18
  return render_template('index.html')

模板中

<ol>
    <li>{{ g.name }}</li>
    <li>{{ g.age }}</li>
  </ol>

(4) 使用 **locals()

@app.route('/')
def index():
  name = '张三'
  age = 18
  print(locals())
  return render_template('index.html',**locals())

模板中

<li>{{ name }}</li>
<li>{{ age }}</li>

十三、url_for 构造绝对的链接地址

@app.route('/test/')
def test():
  print(url_for('index',_external=True))
  return 'test'

十四、加载静态资源

静态资源:图片,css,js,视频,音频,,

实例

<img src="{{ url_for('static',filename='img/17.jpg') }}" alt="">

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
使用python获取CPU和内存信息的思路与实现(linux系统)
Jan 03 Python
详解Python中的__init__和__new__
Mar 12 Python
python使用any判断一个对象是否为空的方法
Nov 19 Python
python使用PIL模块实现给图片打水印的方法
May 22 Python
Python的Django框架中settings文件的部署建议
May 30 Python
Python ftp上传文件
Feb 13 Python
python遍历文件夹下所有excel文件
Jan 03 Python
Python简单计算文件MD5值的方法示例
Apr 11 Python
python之验证码生成(gvcode与captcha)
Jan 02 Python
Python爬虫 批量爬取下载抖音视频代码实例
Aug 16 Python
keras Lambda自定义层实现数据的切片方式,Lambda传参数
Jun 11 Python
pandas 数据类型转换的实现
Dec 29 Python
Sanic框架基于类的视图用法示例
Jul 18 #Python
flask入门之表单的实现
Jul 18 #Python
Flask入门之上传文件到服务器的方法示例
Jul 18 #Python
flask入门之文件上传与邮件发送示例
Jul 18 #Python
Sanic框架流式传输操作示例
Jul 18 #Python
django 发送邮件和缓存的实现代码
Jul 18 #Python
python实现linux下抓包并存库功能
Jul 18 #Python
You might like
php+mysql数据库实现无限分类的方法
2014/12/12 PHP
php中使用url传递数组的方法
2015/02/11 PHP
php防止CC攻击代码 php防止网页频繁刷新
2015/12/21 PHP
ThinkPHP 3使用OSS的方法
2018/07/19 PHP
载入进度条 效果
2006/07/08 Javascript
用js实现预览待上传的本地图片
2007/03/15 Javascript
仿服务器端脚本方式的JS模板实现方法
2007/04/27 Javascript
获得所有表单值的JQuery实现代码[IE暂不支持]
2012/05/24 Javascript
jQuery选择器之基本选择器与层次选择器
2015/03/03 Javascript
Eclipse引入jquery报错如何解决
2015/12/01 Javascript
javascript对象的相关操作小结
2016/05/16 Javascript
纯js实现手风琴效果代码
2020/04/17 Javascript
Bootstrap框架实现广告轮播效果
2016/11/28 Javascript
bootstrap弹出层的多种触发方式
2017/05/10 Javascript
详解Angular5/Angular6项目如何添加热更新(HMR)功能
2018/10/10 Javascript
微信小程序自定义导航栏实例代码
2019/04/05 Javascript
vue跳转同一个组件,参数不同,页面接收值只接收一次的解决方法
2019/11/05 Javascript
jquery获取input输入框中的值
2019/11/13 jQuery
antd中table展开行默认展示,且不需要前边的加号操作
2020/11/02 Javascript
python实现dict版图遍历示例
2014/02/19 Python
python 给DataFrame增加index行名和columns列名的实现方法
2018/06/08 Python
Python日期时间对象转换为字符串的实例
2018/06/22 Python
老生常谈python中的重载
2018/11/11 Python
Python3几个常见问题的处理方法
2019/02/26 Python
简单瞅瞅Python vars()内置函数的实现
2019/09/27 Python
Python:slice与indices的用法
2019/11/25 Python
Python基于当前时间批量创建文件
2020/05/07 Python
html5实现的便签特效(实战分享)
2013/11/29 HTML / CSS
J2EE系统只能是基于web
2015/09/08 面试题
大学生村官考核材料
2014/05/23 职场文书
大型演出策划方案
2014/05/28 职场文书
七夕活动策划方案
2014/08/16 职场文书
校园广播稿100字
2014/10/06 职场文书
山楂树之恋观后感
2015/06/11 职场文书
大学生暑期社会实践的个人总结!
2019/07/17 职场文书
CSS 实现磨砂玻璃(毛玻璃)效果样式
2023/05/21 HTML / CSS