美文网首页
Flask 模板渲染和使用

Flask 模板渲染和使用

作者: candice0430 | 来源:发表于2022-09-07 20:01 被阅读0次

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 模板渲染和使用

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