写flask完整分页导航菜
时间: 2023-07-19 09:16:09 浏览: 108
好的,以下是一个使用 Flask 和 Bootstrap 实现完整分页导航菜单的示例代码:
```python
from flask import Flask, render_template, request
from math import ceil
app = Flask(__name__)
# 模拟数据
data = [
{"id": 1, "name": "John"},
{"id": 2, "name": "Mary"},
{"id": 3, "name": "Tom"},
{"id": 4, "name": "Jane"},
{"id": 5, "name": "Bob"},
{"id": 6, "name": "Kate"},
{"id": 7, "name": "David"},
{"id": 8, "name": "Lily"},
{"id": 9, "name": "Peter"},
{"id": 10, "name": "Lucy"},
{"id": 11, "name": "Mike"},
{"id": 12, "name": "Susan"},
{"id": 13, "name": "Jack"},
{"id": 14, "name": "Sophie"},
{"id": 15, "name": "Chris"},
{"id": 16, "name": "Emma"},
{"id": 17, "name": "Kevin"},
{"id": 18, "name": "Grace"},
{"id": 19, "name": "Frank"},
{"id": 20, "name": "Olivia"}
]
# 每页显示的数据条数
PER_PAGE = 5
@app.route("/")
def index():
# 获取当前页码,如果没有则默认为第一页
page = request.args.get("page", 1, type=int)
# 计算总页数
total_pages = ceil(len(data) / PER_PAGE)
# 获取当前页的数据
start_index = (page - 1) * PER_PAGE
end_index = start_index + PER_PAGE
current_data = data[start_index:end_index]
# 渲染模板
return render_template("index.html", data=current_data, page=page, total_pages=total_pages)
if __name__ == "__main__":
app.run(debug=True)
```
在模板文件 `index.html` 中,你需要使用 Bootstrap 的分页组件来显示分页导航菜单。以下是示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Flask Pagination Example</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1 class="text-center">Flask Pagination Example</h1>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{% for item in data %}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<nav aria-label="Page navigation example">
<ul class="pagination justify-content-center">
{% if page > 1 %}
<li class="page-item"><a class="page-link" href="?page={{ page-1 }}">上一页</a></li>
{% endif %}
{% for i in range(1, total_pages+1) %}
{% if i == page %}
<li class="page-item active"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
{% else %}
<li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
{% endif %}
{% endfor %}
{% if page < total_pages %}
<li class="page-item"><a class="page-link" href="?page={{ page+1 }}">下一页</a></li>
{% endif %}
</ul>
</nav>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body>
</html>
```
在这个示例中,我们使用了 Bootstrap 的分页组件来显示分页导航菜单。在模板文件中,我们使用了 Flask 的模板引擎来动态生成分页链接。当用户点击分页链接时,Flask 会重新加载页面并显示相应的数据。
阅读全文