Flask 模板渲染和使用

Web应用开发,如果想让Python生成Html,实际上非常麻烦,因为我们必须自己进行 HTML 转义以确保应用程序的安全。但 Flask 提供的配置Jinja2模板引擎,却可以很好的帮助到我们。
模板可用于生成任何类型的文本文件。对于 Web 应用程序,将主要生成 HTML 页面,但也可以生成 markdown、电子邮件的纯文本或任何其他内容。本文主要讲解生成HTML页面。

1.render_template()的使用

  • 代码示例:
@bp.route('/register', methods=["GET", "POST"])
def register():
    if request.method == 'GET':
        return render_template("register.html")
  • templates:flask默认会在templates目录下寻找对应的html文件,如下图:


    image.png

2.模板变量:{{变量}}

  • 代码示例:
    index.py:将数据库查询到的questions传入到index.html中的articles

@bp.route('/')
def index():
    questions = QuestionModel.query.all()
    print(questions)
    return render_template('index.html', articles=questions)

index.html:遍历传递过滤的变量articles,通过{{article}}展示变量

 {% for article in articles %}
                    <li>
                        <div class="slide-question">
                            <img class="side-question-avatar" src="{{ url_for("static",filename="images/avtar.jpeg") }}"
                                 alt="">
                        </div>
                        <div class="question-main">
                            <div class="question-title"><a href={{ url_for('qa.question',question_id=article.id) }}>{{ article.title }}</a></div>
                            <div class="question-content"> {{ article.content }} </div>
                            <div class="question-detail">
                                <div class="question-author">{{ article.author.username }}</div>
                                <div class="question-author">{{ article.create_time }}</div>
                            </div>

                        </div>
                    </li>
                {% endfor %}

3.模板表达式:{% %}

  • 代码示例:
{% for item in navigation %}
        <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}

<div>
    {% if True %}
        yay
    {% endif %}
</div>

4.模板可访问对象:config、request、session、g以及函数:url_for()和get_flashed_messages()

  • 访问config:
{{ config.SECRET_KEY }}
image.png
image.png
image.png
  • 访问request:
{{ request.method }}
image.png
  • 访问session
  • 访问g
  • 访问url_for()
<div class="question-title"><a href={{ url_for('qa.question',question_id=article.id) }}>{{ article.title }}</a></div>
  • 访问get_flashed_messages()
//user.py 存放flash信息
@bp.route('/login', methods=["GET", "POST"])
def login():
    if request.method == 'GET':
        return render_template("login.html")
    else:
        login_form = LoginForm(request.form)
        if login_form.validate():
            print("验证通过")
            return redirect("/")
        else:
            print("验证失败", login_form.errors)
            flash("邮箱或密码不正确")
            return redirect(url_for("user.login"))
//login.html 读取flash
{% with messages = get_flashed_messages() %}
                    {% if messages %}
                        <ul class=flashes>
                            {% for message in messages %}
                                <li class="text-danger">{{ message }}</li>
                            {% endfor %}
                        </ul>
                    {% endif %}
                {% endwith %}

5.模板过滤
什么是模板过滤器?

  • 模板过滤器相当于是一个函数,把当前的变量传入过滤器,过滤器根据自己的功能对变量进行相应的处理,再返回对应的值,并将结果渲染到网页中
  • 过滤器是通过管道符号| 来实现的
{{ name|length }}
{{age|abs}}
  • 内置过滤器列表


    image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一.Flask模板中的特殊变量和函数 用途:可以在自己的模板中访问一些Flask默认内置的函数和对象.当然,这些变...
    留白一直在5阅读 4,594评论 0 0
  • Table of Contents WSGIwsgi服务器作用wsgirefhttp协议无状态,短连接,长连接co...
    四月天_da7e阅读 3,301评论 0 0
  • 【Chapter 4】 Web 表单 4.1 跨站请求伪造保护 默认情况下,Flask-WTF 能保护所有表单免受...
    蜘蛛的梦呓阅读 3,414评论 0 2
  • Jinja2模板引擎简介 模板 在前面的实例中,视图函数的主要作用是生成请求的响应,这是最简单请求.实际上,视图函...
    懵懂_傻孩纸阅读 14,851评论 0 7
  • 默认情况下,Flask 在程序文件夹中的 templates 子文件夹中寻找模板。在下一个 hello.py 版本...
    改变自己_now阅读 12,470评论 0 8