模版变量
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): user='valentine' return render_template('index.html',username=user) if __name__ == '__main__': app.debug = True app.run()
在index.py同级目录建立templates文件夹,下新建index.html
<!doctype html> <html> <head> <title>index</title> </head> <body> <h1>Welcome, {{username}}!</h1> </body> <footer> </footer> </html>
{{变量}},将变量传递给html。
模版标签
#coding:utf-8 from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): user='valentine' nav_list=[u'首页',u'经济',u'文化',u'科技',u'娱乐'] return render_template('index.html',username=user,nav_list=nav_list) if __name__ == '__main__': app.debug = True app.run()
传入nav_list参数,因为python不支持ascii码,所以在第一行加上。
<!doctype html> <html> <head> <title>index</title> </head> <body> <h1>Welcome, {{username}}!</h1> {%for nav in nav_list%} <li>{{nav}}</li> {%endfor%} </body> <footer> </footer> </html>
for循环
字典格式数据的遍历
#coding:utf-8 from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): dic={'title':'blog','author':'valentine','date':'2015:06:25'} return render_template('index.html',dic=dic) if __name__ == '__main__': app.debug = True app.run()
html:
<!doctype html> <html> <head> <title>index</title> </head> <body> <div>{{dic['title']}}</div> <div> {%for item in dic%} <li>{{item}}</li> {%endfor%} </div> </body> <footer> </footer> </html>
第一行根据字典的key输出value,循环会取得字典的key,取value应该:
{%for item in dic.values()%}
两者同时取,应该:
{%for key,value in dic.items()%}
访问静态资源,如js,img,css
#coding:utf-8 from flask import Flask, render_template, url_for app = Flask(__name__) @app.route('/') def index(): img = url_for('static', filename='imgs/1.jpg') return render_template('index.html',img=img) if __name__ == '__main__': app.debug = True app.run()
在同级目录建立static文件夹,下面存放静态资源。
模版继承
<html> <head> myBlog </head> <body> <div>Microblog: <a href="/index">Home</a></div> <hr> {% block content %}{% endblock %} </body> </html>
以上为base.html,同级目录index.html继承此模版:
{% extends 'base.html' %} {% block content %} ....content {% endblock %}