我正在尝试在 HTML 中创建一个按钮,单击该按钮时将转到下一页/上一页。我尝试过分页和 peewee 但似乎没有让它工作。
这是我的应用程序:
from flask import Flask,render_template, request, json
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'example'
app.config['MYSQL_USER'] = 'example'
app.config['MYSQL_PASSWORD'] = 'example'
app.config['MYSQL_DB'] = 'fund_raiser'
mysql = MySQL(app)
@app.route('/funds/pages/', defaults={'page':0})
@app.route('/funds/pages/<int:page>')
def fund_pages(page):
perpage = 5
first_page = page*perpage
cur = mysql.connection.cursor()
cur.execute("select * from fund_table limit "+str(first_page)+", "+str(perpage)+";", mysql.connection.commit())
data = cur.fetchall()
return render_template('funds.html', data=data)
我应该在 html 页面的什么位置添加 href 标签?正确使用的变量是什么?
最佳答案
使用 url_for()
函数,这非常简单。
您可以调用该路由的函数名称,并向其传递一个变量。
href="{{ url_for('fund_pages', page=page_num) }}"
其中 page_num
是页码。
要动态获取页码,您可以简单地在当前页码上加或减 1。例如,您可以存储 page_prev = current_page - 1
和 page_next = current_page + 1
。
您可以将这些变量作为 page
参数传递给 url_for
函数。
示例:
# in fund_pages()
prev_page = page - 1
next_page = page + 1
return render_template('template.hmtl', next_page=next_page, prev_page=prev_page)
# in the template
<a href="{{ url_for('fund_pages', page=prev_page) }}">Previous</a>
<a href="{{ url_for('fund_pages', page=next_page) }}">Next</a>
关于python - Python 中的 Flask 分页帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58973137/