flask(三)

模板的使用 template
1.在项目下创建 templates 文件夹,用于存放所有的模板文件,并在目录下创建一个模板html文件 temp_demo1.html

2.设置 templates 文件夹属性以便能够在代码中有智能提示

3.设置 html 中的模板语言,以便在 html 有智能提示

4.创建视图函数,将该模板内容进行渲染返回

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

5.代码中传入字符串,列表,字典到模板中

@app.route('/')
def index():
    # 往模板中传入的数据
    my_str = 'Hello 黑马程序员'
    my_int = 10
    my_array = [3, 4, 2, 1, 7, 9]
    my_dict = {
        'name': 'xiaoming',
        'age': 18
    }
    return render_template('temp_demo1.html',
                           my_str=my_str,
                           my_int=my_int,
                           my_array=my_array,
                           my_dict=my_dict
                           )

6.模板中的代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
我的模板html内容
<br/>{{ my_str }}
<br/>{{ my_int }}
<br/>{{ my_array }}
<br/>{{ my_dict }}

</body>
</html>

Jinjia2 中的If语句和for循环(控制代码块)

1.if判断语句

{%if user.is_logged_in() %}
    <a href='/logout'>Logout</a>
{% else %}
    <a href='/login'>Login</a>
{% endif %
1.2.过滤器可以被用在 if 语句中:
{% if comments | length > 0 %}
    There are {{ comments | length }} comments
{% else %}
    There are no comments
{% endif %}

2.for循环语句

2.1    Jinja2 中使用循环来迭代任何列表或者生成器函数

{% for post in posts %}
    <div>
        <h1>{{ post.title }}</h1>
        <p>{{ post.text | safe }}</p>
    </div>
{% endfor %}

2.2    循环和if语句可以组合使用,以模拟 Python 循环中的 continue 功能,下面这个循环将只会渲染post.text不为None的那些post:

{% for post in posts if post.text %}
    <div>
        <h1>{{ post.title }}</h1>
        <p>{{ post.text | safe }}</p>
    </div>
{% endfor %}

 

posted @ 2021-09-17 10:04  鯊鱼  阅读(24)  评论(0)    收藏  举报