shogun000
shogun000

Reputation: 303

Pagination in flask is not working

I have been trying to add pagination to my flask app following this tutorial: http://flask.pocoo.org/snippets/44/.

It seems to be working now, as I can visit the separated items on each page manually by going to: http://localhost:5000/page/x.

But I can't seem to get jinja2 to render the links as the snippet does.

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 %}

Is there anything wrong with my queries?

Upvotes: 0

Views: 2354

Answers (1)

dirn
dirn

Reputation: 20729

render_pagination is a macro, a reusable block of code (function) that can be used by many templates. You'll typically want to define them in a separate template file (or files if you have many).

# 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 %}

Then, in your template, you can import and use the macro.

# index2.html

{% from macros import render_pagination %}

{% block content %}
  ... content here ...

  {{ render_pagination(pagination) }}
{% endblock %}

Upvotes: 1

Related Questions