美文网首页
20. Flask 模板控制语句 if for

20. Flask 模板控制语句 if for

作者: Devops海洋的渔夫 | 来源:发表于2019-12-19 18:55 被阅读0次

Flask在模板中有常用的几种控制语句:

  • if控制语句
  • for控制语句

下面来看看示例加强理解,如下:

模板中的if控制语句

1. 示例视图函数

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

2.示例模板

 <html>
 <head>
     {% if user %}
        <title> hello {{user}} </title>
    {% else %}
         <title> welcome to flask </title>        
    {% endif %}
 </head>
 <body>
     <h1>hello world</h1>
 </body>
 </html>

模板中的for循环语句

1. 示例视图函数

 @app.route('/loop')
 def loop():
    fruit = ['apple','orange','pear','grape']
    return render_template('loop.html',fruit=fruit)

2.示例模板

<html>
 <head>
     {% if user %}
        <title> hello {{user}} </title>
    {% else %}
         <title> welcome to flask </title>        
    {% endif %}
 </head>
 <body>
     <h1>hello world</h1>
    <ul>
        {% for item in fruit %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
 </body>
 </html>

相关文章

网友评论

      本文标题:20. Flask 模板控制语句 if for

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