美文网首页
《Flask Web开发实战》——模板

《Flask Web开发实战》——模板

作者: 北邮郭大宝 | 来源:发表于2019-11-11 22:58 被阅读0次

本书第三章Flask之template,对一些内容做个笔记,方便回顾。

1. 模板基本用法

  • Flash默认的模板引擎是jinja2
  • 借助render_template()完成渲染,传入的参数几乎可以是任何Python对象
  • jinja
    • 语句 {% %}
    • 表达式 {{ }}
    • 注释 {# #}

2. 模板辅助工具

  • 上下文
    • 内置上下文:config、request、session、g
    • 自定义上下文:app.context_processor
  • 全局对象
    • 内置函数
    • 自定义全局函数 app.template_global()
  • 过滤器
    • 内置过滤器 length、wordcount等
    • 自定义过滤器 app.template_filter()
  • 测试器
    • 内置测试器 number、iterable
    • 自定义测试器 app.template_test()

3. 模板结构组织

  • 局部模板 {% include '_XX.html' %}
  • 宏 {% macro % } {% endmacro %}
  • 模板继承 {% extends 'base.html' %}

4. 模板进阶实践

  • 加载静态文件
  • flash
  • 自定义错误页面 app.errorhandler()

5. code

5.1 app.py


# coding=utf-8
from flask import Flask, render_template, Markup, flash, redirect, url_for
import os


app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY', 'SIT')


user = {
    'username': 'Dabao Guo',
    'bio': 'A boy who loves movies and music.',
}

movies = [
    {'name': 'My Neighbor Totoro', 'year': '1988'},
    {'name': 'Three Colours trilogy', 'year': '1993'},
    {'name': 'Forrest Gump', 'year': '1994'},
    {'name': 'Perfect Blue', 'year': '1997'},
    {'name': 'The Matrix', 'year': '1999'},
    {'name': 'Memento', 'year': '2000'},
    {'name': 'The Bucket list', 'year': '2007'},
    {'name': 'Black Swan', 'year': '2010'},
    {'name': 'Gone Girl', 'year': '2014'},
    {'name': 'CoCo', 'year': '2017'},
]


@app.route('/')
@app.route('/watchlist')
def watchlist():
    return render_template('watchlist.html', user=user, movies=movies)


@app.route('/index')
def index():
    return render_template('index.html')


# 自定义上下文
@app.context_processor
def inject_info():
    foo = 'i am foo'
    return dict({'foo': foo})


# 自定义全局函数
@app.template_global()
def bar():
    return 'I am bar'


# 自定义过滤器
@app.template_filter()
def musical(s):
    return s + Markup(' &#9835')


# 自定义过滤器
@app.template_test()
def is_year(year):
    if str(year) == '1994':
        return True
    else:
        return False


# flash
@app.route("/flash")
def just_flash():
    flash("你好,我是flash, 你是谁?")
    return redirect(url_for('index'))


# 错误处理函数
@app.errorhandler(404)
def page_not_found(e):
    return render_template("errors/404.html"), 404

5.2

  • base.html
<!DOCTYPE html>
<html lang="en">
<head>
    {% block head %}
        <meta charset="UTF-8">
        <title>{% block title %} Template - helloflask {% endblock title%}</title>
        <link rel="icon" type="image/x-icon" href="{{ url_for('static', filename='favicon.ico') }}">
        {% block styles %}
            <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css' ) }}">
        {% endblock styles%}
    {% endblock %}
</head>
<body>
    <nav>
        <ul><li><a href="{{ url_for('index')}}">Home</a></li></ul>
    </nav>
    <main>
        {% for message in get_flashed_messages() %}
        <div class="alert"> {{ message }}</div>
        {% endfor %}
        {% block content %} {% endblock content%}
    </main>
    <footer>
        {% block footer %}
        <small> &copy; 2019 </small>
        {% endblock footer%}
    </footer>
    {% block scripts %} {% endblock scripts%}
</body>
</html>
  • index.html
{% extends 'base.html' %}
{% from 'macro.html' import qux %}

{% block title %} Home {% endblock title %}

{% block content %}
<h1>Template</h1>
<ul>
    <li><a href= "{{ url_for('watchlist') }}">WatchList</a></li>
    <li>Filter: {{ foo|musical }}</li>
    <li>Global: {{ bar() }}</li>
    <li>Macro: {{ qux(amount=5) }}</li>
    <li><a href="{{ url_for('just_flash') }}">Flash something</a></li>
</ul>
{% endblock content %}

{% block styles %}
{{ super() }}
<style>
    .b {
        color: red;
    }
</style>
{% endblock styles %}

相关文章

网友评论

      本文标题:《Flask Web开发实战》——模板

      本文链接:https://www.haomeiwen.com/subject/wiixictx.html