【问题标题】:Pagination in flask is not working烧瓶中的分页不起作用
【发布时间】:2015-08-22 20:00:00
【问题描述】:

我一直在尝试按照本教程为我的烧瓶应用程序添加分页:http://flask.pocoo.org/snippets/44/

现在似乎可以正常工作了,因为我可以通过以下方式手动访问每个页面上的单独项目:http://localhost:5000/page/x

但我似乎无法让 jinja2 像 sn-p 那样呈现链接。

views.py

POSTS_PER_PAGE = 3
@app.route('/', defaults={'page': 1})
@app.route('/page/<int:page>')
def homepage(page):
  todayDate = datetime.utcnow()
  yesterdayDate = datetime.utcnow() - timedelta(days=1)
  count = Post.query.count()
  posts = Post.query.order_by(Post.posted_on.desc()).paginate(page,POSTS_PER_PAGE, count).items
  by_date = it.groupby(posts, key=lambda p:p.posted_on)

  pagination = Pagination(page, POSTS_PER_PAGE, count)
  return render_template('index2.html',
                            by_date=by_date,
                            todayDate=todayDate,
                            yesterdayDate=yesterdayDate,
                            pagination=pagination)

index2.html

{% block content %}
 .. content here ..
{% macro render_pagination(pagination) %}
  <div class=pagination>
  {%- for page in pagination.iter_pages() %}
    {% if page %}
      {% if page != pagination.page %}
        <a href="{{ url_for_other_page(page) }}">{{ page }}</a>
      {% else %}
        <strong>{{ page }}</strong>
      {% endif %}
    {% else %}
      <span class=ellipsis>…</span>
    {% endif %}
  {%- endfor %}
  {% if pagination.has_next %}
    <a href="{{ url_for_other_page(pagination.page + 1)
      }}">Next &raquo;</a>
  {% endif %}
  </div>
{% endmacro %}
{% endblock %}

我的查询有什么问题吗?

【问题讨论】:

    标签: python flask pagination


    【解决方案1】:

    render_pagination 是一个macro,一个可被许多模板使用的可重用代码块(函数)。您通常希望在单独的模板文件(或多个文件,如果有的话)中定义它们。

    # macros.html
    
    {% macro render_pagination(pagination) %}
      <div class=pagination>
      {%- for page in pagination.iter_pages() %}
        {% if page %}
          {% if page != pagination.page %}
            <a href="{{ url_for_other_page(page) }}">{{ page }}</a>
          {% else %}
            <strong>{{ page }}</strong>
          {% endif %}
        {% else %}
          <span class=ellipsis>…</span>
        {% endif %}
      {%- endfor %}
      {% if pagination.has_next %}
        <a href="{{ url_for_other_page(pagination.page + 1)
          }}">Next &raquo;</a>
      {% endif %}
      </div>
    {% endmacro %}
    

    然后,在您的模板中,您可以导入和使用宏。

    # index2.html
    
    {% from macros import render_pagination %}
    
    {% block content %}
      ... content here ...
    
      {{ render_pagination(pagination) }}
    {% endblock %}
    

    【讨论】:

      猜你喜欢
      • 2016-12-23
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      相关资源
      最近更新 更多