标签:python
服务端代码
#在模板中我们能不能使用for循环,能不能使用if条件控制语句?答案是肯定的。除了流程控制语句外,这里还将讲述用面向对象的思想来写模板文件。 #服务端代码: #coding:utf-8 from flask import Flask, render_template app = Flask(__name__) @app.route(‘/‘) def index(): ‘‘‘访问首页‘‘‘ var_list = [‘tantianran‘,‘1234‘,‘元素a‘,‘aaaa‘,‘元素b‘] var_tuple = ("laowang","tantianran","dengwenqing") var_dict = {"key1":"value1","name":"tanzhenxing"} return render_template("example.html", var_list = var_list, var_tuple = var_tuple, var_dict = var_dict ) if __name__ == ‘__main__‘: app.run(debug=True)
前端代码:
前端代码(templates/example.html): <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>jinjia2模板for标签的使用</title> <link rel="stylesheet" type="text/css" href=""> </head> <body> <header id="header" class=""> <h1>导航栏</h1> </header> <!-- 作者:996298929@qq.com 时间:2017-05-15 描述:/header --> <article> <h1>遍历后端传过来的列表</h1> <ul> {% for item in var_list %} <li>{{ loop.index }} {{ item }}</li> {% endfor %} </ul> <h1>遍历后端传过来的元组</h1> <ul> {% for item in var_tuple %} <li>{{ loop.index }} {{ item }}</li> {% endfor %} </ul> <h1>遍历后端传过来的字典</h1> <ul> {% for k,v in var_dict.items() %} <li>{{ loop.index }} {{ k,v }}</li> {% endfor %} </ul> </article> <footer> <h3>页脚部分</h3> </footer> </body> </html>
二、if标签
服务端代码:
#coding:utf-8 from flask import Flask, render_template app = Flask(__name__) @app.route(‘/user/‘) @app.route(‘/user/<uname>‘) def user(uname=None): ‘‘‘用户测试‘‘‘ return render_template(‘label_user.html‘, uname=uname) if __name__ == ‘__main__‘: app.run(debug=True)
前端代码:
前端代码(templates/label_user.html): <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>jinjia2模板if标签学习</title> <link rel="stylesheet" type="text/css" href=""> </head> <body> {% if uname %} <h1>你好!,{{ uname }},欢迎访问</h1> {% else %} <h1>你好,我不认识你</h1> {% endif %} </body> </html>
三、页面的复用(jinjia2继承,页面继承)
服务端代码:
#coding:utf-8 from flask import Flask, render_template app = Flask(__name__) @app.route(‘/basetest/‘) def basetest(): ‘‘‘用户测试‘‘‘ return render_template(‘new_index.html‘) if __name__ == ‘__main__‘: app.run(debug=True)
前端代码:
前端代码: 1、templates/base.html <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> {% block title %} <title>这是基础页面</title> {% endblock %} <link rel="stylesheet" type="text/css" href=""> </head> <body> <header id=header class=""> <h1>导航栏</h1> </header> <article> {% block content%} 内容区域 {% endblock %} <!--继承独立的页脚部分的html--> {% include ‘footer.html‘ %} </article> </body> </html> 2、templates/footer.html <footer> <h3>页脚部分</h3> </footer> 3、templates/new_index.html <!--继承base.html页面--> {% extends ‘base.html‘ %} <!--重写base.html页面中的title--> {% block title %} <title>12345</title> {% endblock %} <!--重写base.html页面中的内容区域--> {% block content%} 内容 哈哈哈 {% endblock %}
本文出自 “Fresh Air Team” 博客,请务必保留此出处http://freshair.blog.51cto.com/8272891/1927426
标签:python
原文地址:http://freshair.blog.51cto.com/8272891/1927426