html
文件,用于快速开发 web 页面
templates
默认在项目路径下,也可自定义,如下:
# template_folder:定义模板的位置
app = Flask(__name__,template_folder=r'C:\templates')
xx.html
和 xx.py
即可index.html:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
我的模板html内容:<br/>
{{ name }} <br/>
{{ age }}
body>
html>
其中
{{ }}
表示引用变量
app.py:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
name = '张三'
age = 18
return render_template('index.html',
name=name,
age=age)
if __name__ == '__main__':
app.run(debug=True)
index.html:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<table border="1" cellspacing="0" cellpadding="2">
<tr>
<th>姓名th>
<th>年龄th>
<th>性别th>
tr>
<tbody>
{% for l in test_list %}
<tr>
<td> {{ l['name'] }}td>
<td> {{ l['age'] }}td>
<td> {{ l['sex'] }}td>
tr>
{% endfor %}
tbody>
table>
body>
html>
app.py:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
test_list = [{'name': '张三', 'age': 18, 'sex': '女'},
{'name': '李四', 'age': 19, 'sex': '男'},
{'name': '王五', 'age': 20, 'sex': '女'}]
return render_template('login.html',
test_list=test_list)
if __name__ == '__main__':
app.run(debug=True)
index.html:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
{% if name == '张三' %}
<p> 我是 {{ name }} p>
{% elif name == '李四' %}
<p> 她是 {{ name }} p>
{% else %}
<p> 不认识p>
{% endif%}
table>
body>
html>
app.py:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
name = '张三'
return render_template('login.html',
name=name)
if __name__ == '__main__':
app.run(debug=True)
浏览器访问结果:
# 继承来自 base.html 的样式
{% extends "base.html" %}
# 数据格式
{% block 自定义名称 %}
自定义内容
{% endblock %}
base.html:公共部分
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>公共部分title>
<style type="text/css">
.container {
width: 600px;
height: 500px;
margin: 0 auto;
}
header {
background: blue;
}
article {
background: white;
height: 500px;
}
footer {
background-color: red;
}
style>
head>
<body>
<div class="container">
<header>
{% block header %}
{% endblock %}
header>
<article>
{% block content %}
{% endblock %}
article>
<footer>
{% block footer %}
123
{% endblock %}
footer>
div>
body>
html>
index.html 首页部分
{% extends 'base.html' %}
{% block header%}
首部
{% endblock %}
{% block content %}
内容
{% endblock %}
{% block footer %}
尾部
{% endblock %}
app.py:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
{% block footer %}
{{ super() }}
尾部
{% endblock %}